我正在准备升级到React 16的React组件,其中关键是要更新与React.createClass
一起使用class
关键字的组件。从createClass转换为class关键字时,如何正确绑定React组件类的事件处理程序?
当我遇到Can only update a mounted or mounting component
错误时,遇到引发类方法的事件处理程序时,我遇到了麻烦。使用React.createClass
一个简单的例子...
原来的分量:
const Foo = React.createClass({
getInitialState() {
return { bar: false };
},
onClick() {
this.setState({ bar: !this.state.bar });
},
render() {
return (
<div>
<p>{this.state.bar ? 'YAY' : 'BOO'}</p>
<button onClick={this.onClick}>CLICK IT</button>
</div>
);
},
});
按预期工作。那么,这是否,如果我愿意忽略一个新的函数对象将与每次调用创建render
:
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { bar: false };
}
render() {
return (
<div>
<p>{this.state.bar ? 'YAY' : 'BOO'}</p>
<button onClick={() => { this.setState({ bar: !this.state.bar }); }}>CLICK IT</button>
</div>
);
}
}
但是,我不能得到的“在构造函数中结合”的工作方式:
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { bar: false };
this.onClick = this.onClick.bind(this);
}
onClick() {
this.setState({ bar: !this.state.bar });
}
render() {
return (
<div>
<p>{this.state.bar ? 'YAY' : 'BOO'}</p>
<button onClick={this.onClick}>CLICK IT</button>
</div>
);
}
}
我也不能获得属性初始化语法的工作方式:
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { bar: false };
}
onClick =() => {
this.setState({ bar: !this.state.bar });
}
render() {
return (
<div>
<p>{this.state.bar ? 'YAY' : 'BOO'}</p>
<button onClick={this.onClick}>CLICK IT</button>
</div>
);
}
}
在这两种这些情况下,每当我按一下按钮前面提到的错误消息显示了我浏览器控制台。
我希望有人自己已经遇到过这个问题,并且就如何处理它提出了建议。我想,这完全忽略了一些微不足道的东西。 :)
在此先感谢!
你可以尝试'的onClick(){ this.setState((prevState)=>({吧!prevState.bar})); }' –
这是一个单独的问题;任何绑定方法都能正常工作 –
要使类属性有效,您需要对其进行转换。它们现在不包含在Babel预设中,因为它们仍然是一个建议。你需要启用[stage-2](https://babeljs.io/docs/plugins/preset-stage-2/)。 –