在create-react-app建立的項目下容許函數綁定運算符

前話

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

相關文章
相關標籤/搜索