[英]In React project, “this” converts into “undefined”
A very simple code 一个非常简单的代码
var App = React.createClass({
handleForm: (e) => {
e.preventDefault();
},
render: () => {
return (
<form>
<button type="submit" onClick={this.handleForm}>Go</button>
</form>
);
}
});
Gets converted into 转换成
// ...
_react2['default'].createElement(
'button',
{ type: 'submit', onClick: undefined.handleFormSubmit },
'Go'
)
But why? 但为什么? And do I need to bind all the things explicitly (including
this.setState
which I can't get working for the same reason)? 我是否需要显式绑定所有事物(包括
this.setState
相同原因而无法使用的this.setState
)?
I'm using react 0.13.3 with webpack 1.12.2 and babel-loader 5.3.2. 我正在使用带有Webpack 1.12.2和babel-loader 5.3.2的react 0.13.3。 Haven't faced such a problem before.
以前没有遇到过这样的问题。
When you use an arrow function as the value of a property in an object literal, the binding to this
is that of the function's declaration scope just like any arrow function. 当您使用箭头函数作为对象文字中属性的值时,
this
的绑定就是该函数的声明范围的绑定,就像任何箭头函数一样。 In ES6 module code the value of this
in the outermost context is defined to be undefined
so Babel is simply inlining this value. 在ES6模块代码中,最外层上下文中的
this
的值被定义为undefined
因此Babel只是内联该值。 What you want to do is this: 您要做的是:
var App = React.createClass({
handleForm(e) {
e.preventDefault();
},
render() {
return (
<form>
<button type="submit" onClick={this.handleForm}>Go</button>
</form>
);
}
});
As a final note, you do not need to bind any member functions when using React.createClass
as React will do this for you automatically and in a more efficient way than with Function.prototype.bind
. 最后一点,当您使用
React.createClass
时,您不需要绑定任何成员函数,因为React会比Function.prototype.bind
更加自动高效地为您完成此操作。
Thank you @loganfsmyth for the update about why this
is undefined
. 感谢您@loganfsmyth有关为什么更新
this
是undefined
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.