[英]How can I properly bind a React component class's event handlers when converting from createClass to the class keyword?
我正在准备将React组件升级到React 16,该过程的症结在于更新了与React.createClass
一起使用class
关键字的组件。
在涉及调用类方法的事件处理程序时,我遇到了麻烦,因为我不断看到“ 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
都会创建一个新的函数对象,也可以这样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>
);
}
}
在这两种情况下,每当我单击按钮时,上述错误消息都会显示在浏览器控制台中。
我希望有人已经自己遇到了这个问题,并且对如何处理它有建议。 我想这只是我完全忽略的琐碎事情。 :)
提前致谢!
看一下React文档:他们有相同的示例。 顺便说一句,您的绑定示例对我有用:发布您的错误消息。
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
Pshh,做到这一点很简单,并使用react-autobind 。 结合所有的组件功能, this
在构造自动为您。
超级简单易用:
import autoBind from 'react-autobind';
constructor() {
super();
autoBind(this);
}
在将某些代码从电子应用程序移植到网络后出现了这个确切的问题。
您需要"transform-es2015-classes"
!
npm install --save-dev babel-plugin-transform-es2015-classes
更多信息@ babel docs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.