我知道setState()
不会立即变异 this.state
.因此,在下面的代码中,单击按钮后复选框始终处于未选中状态。如何解决这个问题?
handleClick = () => {
this.setState({tick: !this.state.tick})
}
render() {
return (
<button type='button' onClick={() => this.handleClick()} >
<input type="checkbox" value={this.state.tick} />
Tick here
</button>
)
}
最佳答案
使用 checked
而不是 value
:
<input type="checkbox" checked={this.state.tick} />
来自 spec :
checked
: Boolean; if present, the checkbox is currently toggled on
value
: The string to use as the value of the checkbox when submitting the form, if the checkbox is currently toggled on
关于javascript - 在 setState() 之后立即获取状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53825999/