使用 ES7 Decorators 简化this的绑定
文章目录
1.修改babelrc文件
{
"presets": ["es2015", "react", "stage-1"],
"plugins": ["transform-decorators-legacy"]
}
2.安装 decorator 插件
npm i -S babel-plugin-transform-decorators-legacy
3.修改webpack中loader的配置
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules\/(?!(stardust))/,
loader: 'babel',
query: {
cacheDirectory: true,
plugins: [
'transform-runtime',
'add-module-exports',
'transform-decorators-legacy',
],
presets: ['es2015', 'react', 'stage-1'],
},
}
]
}
4.安装autobind 的库
npm install autobind-decorator
5.写法改进
class MyClass extends Component {
constructor(props, context) {
this.onChange = this.onChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.state = {isLoading: true}
}
onChange() {}
handleSubmit() {}
}
class MyClass extends Component {
state = {isLoading: true}
@autobind
onChange() {}
@autobind
handleSubmit() {}
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论