一、使用bind绑定this
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// 为了在回调中使用 `this`,这个绑定是必不可少的
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? ‘ON‘ : ‘OFF‘}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById(‘root‘)
);
二、class fields语法
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
}
//class fields语法
handleClick = () => {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? ‘ON‘ : ‘OFF‘}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById(‘root‘)
);
三、在回调中使用箭头函数
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={(e) => this.handleClick(e)}>
{this.state.isToggleOn ? ‘ON‘ : ‘OFF‘}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById(‘root‘)
);
注意:语法3中回调函数作为props传入子组件时,这些组件可能会额外重新渲染,所以我们建议使用1、2语法来避免出现性能问题