Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React项目中,“;这";转换为;“未定义”;_Javascript_Gruntjs_Reactjs_Webpack_Babeljs - Fatal编程技术网

Javascript 在React项目中,“;这";转换为;“未定义”;

Javascript 在React项目中,“;这";转换为;“未定义”;,javascript,gruntjs,reactjs,webpack,babeljs,Javascript,Gruntjs,Reactjs,Webpack,Babeljs,一个非常简单的代码 var App = React.createClass({ handleForm: (e) => { e.preventDefault(); }, render: () => { return ( <form> <button type="submit" onClick={this.handleForm}>Go</butto

一个非常简单的代码

var App = React.createClass({
    handleForm: (e) => {
        e.preventDefault();
    },
    render: () => {
        return (
            <form>
                <button type="submit" onClick={this.handleForm}>Go</button>
            </form>
        );
    }
});
但是为什么呢?我需要显式地绑定所有的东西吗(包括
this.setState
,因为同样的原因我不能使用它)


我将react 0.13.3与webpack 1.12.2和babel loader 5.3.2一起使用。以前从未遇到过这样的问题。

当您使用arrow函数作为对象文本中属性的值时,与任何arrow函数一样,对
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>
    );
  }
});
var-App=React.createClass({
手模(e){
e、 预防默认值();
},
render(){
返回(
去
);
}
});
最后,当使用
React.createClass
时,您不需要绑定任何成员函数,因为React将以比使用
Function.prototype.bind
更高效的方式自动为您绑定


感谢@loganfsmyth更新了
未定义

在本例中,导致
未定义
的并非严格模式。Babel将所有内容解析为ES6模块,并且在规范中,ES6模块中的
是明确的
未定义的
。@loganfsmyth在模块代码中定义为
未定义的
不是因为规范将其定义为严格模式吗?道歉!感谢@JMMStrict mode为函数调用定义了
行为,其中包括使用
未定义的
/
null
调用函数不会转换为全局,但模块不是函数。定义全局环境中的
是实际的全局对象,并明确表示模块环境中的
未定义的
。明白了!谢谢你提供的详细参考资料,我会更新我的答案,使之更准确。
var App = React.createClass({
  handleForm(e) {
    e.preventDefault();
  },
  render() {
    return (
        <form>
            <button type="submit" onClick={this.handleForm}>Go</button>
        </form>
    );
  }
});