React的函数绑定一致是个问题,主要有下面几种方式:html
export default class Com extends React.Component { render() { <input type="button" value="点我" onClick={this.method.bind(this)} /> } }
export default class CartItem extends React.Component { constructor(props) { super(props); this.method = this.method.bind(this); } render() { <input type="button" value="点我" onClick={this.method} /> } }
export default class CartItem extends React.Component { const method2 = () =>{...} constructor(props) { super(props); this.method = (ev) => {...} } render() { <input type="button" value="点我" onClick={this.method} /> } }
这个是babel支持的,还不是标准react
export default class CartItem extends React.Component { method = () => {...}; render() { <input type="button" value="点我" onClick={this.method} /> } }
export default class CartItem extends React.Component { method(){...}; render() { <input type="button" value="点我" onClick={::this.method} /> } }
最后一种很帅气, 然并软,我使用就直接报错。 臣不服,不服。
因而寻找方案, 由于是create-react-app建立的项目。
个人思考方案以下webpack
const rewireMobX = require('react-app-rewire-mobx'); const rewireEslint = require('react-app-rewire-eslint'); const {injectBabelPlugin} = require('react-app-rewired'); /* config-overrides.js */ module.exports = { webpack: function override(config, env) { config = rewireEslint(config, env); config = rewireMobX(config, env); config = injectBabelPlugin('transform-function-bind',config) config.output.publicPath = '' return config; } }
修改完毕,启动,哦,能够。 真是不错。
扔掉键盘,甩开鼠标,深深的一口水,想写行代码咋这么难。git
React and ES6 - Part 3, Binding to methods of React class (ES7 included)
decorator
create-react-app
how-to-use-custom-babel-presets
Adding support for custom babel configuration #1357
react-app-rewired
injectbabelplugin
babel-preset-stage-0
babel-plugin-transform-function-bindes6