【发布时间】:2018-07-24 11:31:47
【问题描述】:
在使用 React 时,我已经理解它,因此在组件的渲染方法中调用 setState 是不好的做法;而是保持这种方法纯粹。但是,如果我需要根据链接到组件的事件更新状态,我该怎么做?
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>
);
}
}
以上代码来自 React 的官方教程。正如我们所看到的,一个事件处理程序绑定到 onClick 属性,并且在这个事件处理程序内部,组件的状态发生了变化,因此我们可能会在从渲染方法调用时更新状态。因此,对于为什么可以这样做但没有在 render 方法中显式调用 setState ,我有点迷茫?这与 React 如何包装普通的 html 事件有关吗?
【问题讨论】:
标签: javascript reactjs event-handling render setstate