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}@autobindonChange() {}@autobindhandleSubmit() {}
}