在React项目中,“this”"转换为“未定义”

In React project, "this" converts into "undefined"

本文关键字:未定义 quot 转换 this React 项目      更新时间:2023-09-26

一个非常简单的代码

var App = React.createClass({
    handleForm: (e) => {
        e.preventDefault();
    },
    render: () => {
        return (
            <form>
                <button type="submit" onClick={this.handleForm}>Go</button>
            </form>
        );
    }
});

被转换成

// ...
_react2['default'].createElement(
    'button',
    { type: 'submit', onClick: undefined.handleFormSubmit },
    'Go'
)

但是为什么呢?我需要绑定所有的东西明确(包括this.setState,我不能得到工作同样的原因)?

我使用react 0.13.3与webpack 1.12.2和babel-loader 5.3.2。我从来没有遇到过这样的问题。

当您使用箭头函数作为对象文字中的属性值时,到this的绑定是函数声明范围的绑定,就像任何箭头函数一样。在ES6模块代码中,this在最外层上下文中的值被定义为undefined,因此Babel只是内联这个值。你要做的是:

var App = React.createClass({
  handleForm(e) {
    e.preventDefault();
  },
  render() {
    return (
        <form>
            <button type="submit" onClick={this.handleForm}>Go</button>
        </form>
    );
  }
});

作为最后的注意事项,当使用React.createClass时,您不需要绑定任何成员函数,因为React会自动为您完成此操作,并且比使用Function.prototype.bind更有效。

感谢@loganfsmyth更新thisundefined的原因