ES6+react.js 中定義公共方法、常量
阿新 • • 發佈:2020-07-21
ES6+react.js 中定義公共方法、常量
1、公共方法
1.1 constantFunction.js 檔案(不用寫class域中)
// 解析時間 將時間戳變成可讀的string const parseTime = (text)=>{ if(!!text && typeOf(text) === 'number'){ let createDate = new Date(text); let createTime = createDate.getFullYear() + '-' + (createDate.getMonth()+1)+ '-'+ createDate.getDate()+'-'+ createDate.getHours()+':'+ createDate.getMinutes() + ':' + createDate.getSeconds(); return createTime } } const demo1 = (text)=>{ console.loog('demo1', text) } /// 匯出 export {parseTime,demo1}
1.2 constantFunction.js 檔案中方法的使用
import REact from 'react' import {parseTime,demo1} from ./constantFunction.js class demo extends React.Component{ handleDemo=()=>{ const text = Date.parse(new Date());// 獲取當前時間戳 1595326484000 console.log('handleDemo', parseTime(text) ) //列印: handleDemo,2020-7-21-18:14:44 } }
2、 常量
2.1 Constant.js檔案:
const prefix ='prefix1';// 常量 // 常量1 const namespaces1 = { NAMESPANCE_NAME: `${prefix}_name` , NAMESPANCE_MENU: 'abcdefg' , }; // 常量2 const namespaces2 ={ NAMESPANCE_NAME2: `${prefix}_name2` , NAMESPANCE_MENU2: `${prefix}_MENU2` }; export default Object.assign({}, namespaces,namespaces2 // 所有的變數都在這裡export匯出 多個用逗號隔開 )
2.2 constant.js 檔案中常量的引用:
import REact from 'react'
import Constant from ./constant.js
class demo extends React.Component{
handleDemo=()=>{
console.log('constant.NAMESPANCE_NAME', Constant.NAMESPANCE_NAME )
//列印: prefix1_name
}
}