【发布时间】:2021-07-25 00:51:21
【问题描述】:
我正在学习 React.js 并阅读 react.js 官方文档。官方文档提供了一个示例,我对此有疑问:
原代码:
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')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
我的问题是: 在handleClick方法中,为什么this.setState不能写成(没有箭头函数):
handleClick() {
this.setState({
isToggleOn: !prevState.isToggleOn
});
}
【问题讨论】:
-
你可以,只要你使用
isToggleOn: !this.state.isToggleOn(因为现在你在你的例子中凭空提取prevState,而在页面的示例代码中, setState 被调用可调用函数,该变量是函数的参数,由 React 自动填充)
标签: javascript reactjs