插件,讓代碼更優雅
1. babel-plugin-transform-decorators-legacy
這幾天在補高階組件的相關知識,對于高階組件的引用方式,感覺有些別扭,若是需要引用多個高階組件,必定需要套娃。
根據官方說明,這個插件適用于babel@6.x,如果你正在使用babel@7.x,可以使用@babel/plugin-proposal-decorators。
安裝和使用
$ npm install --save-dev babel-plugin-transform-decorators-legacy
在package.json中配置
"babel": {
"presets": [
"react-app"
],
"plugins": [
"transform-decorators-legacy"
]
},
注意點
如果在項目中還是用了transform-class-properties
,請保證transform-decorators-legacy
在前
// right
"plugins": [
"transform-decorators-legacy",
"transform-class-properties"
]
react中的實際使用
我自己在使用高階組件的時候,會用到這個插件,讓代碼看起來更優雅,不過最常用的應該是withRouter,畢竟路由切換是最常用的業務
// 原有寫法
import React from 'react';
import { usernameHoc } from '@/hoc'
const GoodBye = props => {
return <div>GoodBye {props.username}</div>
}
export default usernameHoc(GoodBye);
// 新的寫法
import React from 'react';
import { usernameHoc } from '@/hoc'
@usernameHoc
const GoodBye = props => {
return <div>GoodBye {props.username}</div>
}
export default GoodBye;
2. babel-plugin-transform-class-properties
接上一個插件中提到的
transform-class-properties
這個插件也是react中文站介紹PropTypes時推薦的,可以試用一下。
官方定義
該插件可轉換es2015靜態類屬性以及使用es2016屬性初始化程序語法聲明的屬性。(轉化為各大瀏覽器的支持的es5語法)
安裝和使用
npm install --save-dev babel-plugin-transform-class-properties
"babel": {
"presets": [
"react-app"
],
"plugins": [
"transform-decorators-legacy",
"transform-class-properties"
]
},
react中的實際使用
可以將props檢測和defaultProps聲明寫在class內部,更優雅。
class Para extends React.Component {
constructor(props){
super(props)
this.state = {
para: '123'
}
}
static defaultProps = {
name: 'stranger'
}
static propTypes = {
name: PropTypes.string.isRequired
}
render(){
return <div>
{this.props.name}
<p>{this.state.para}</p>
</div>
}
}