ES6+react.js 中定義公共方法、常量


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
    }
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM