1.修改babelrc文件node
{ "presets": ["es2015", "react", "stage-1"], "plugins": ["transform-decorators-legacy"] }
2.安裝 decorator 插件react
npm i -S babel-plugin-transform-decorators-legacy
3.修改webpack中loader的配置webpack
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 的庫web
npm install autobind-decorator
5.寫法改進npm
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() {} }