[英]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.