在 React 项目中,"this" 转换为 "undefined"
In React project, "this" converts into "undefined"
一个非常简单的代码
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
,出于同样的原因我无法工作)?
我正在使用带有 webpack 1.12.2 和 babel-loader 5.3.2 的 React 0.13.3。以前没遇到过这样的问题。
当你在对象字面量中使用箭头函数作为 属性 的值时,到 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 更新为什么 this
是 undefined
。
一个非常简单的代码
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
,出于同样的原因我无法工作)?
我正在使用带有 webpack 1.12.2 和 babel-loader 5.3.2 的 React 0.13.3。以前没遇到过这样的问题。
当你在对象字面量中使用箭头函数作为 属性 的值时,到 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 更新为什么 this
是 undefined
。