JSX部分看起来像这样:
<span className="header_srh_i_c" onMouseDown={this.toggleSearchbar}>
<i className="fa fa-search"
id="searchButton"
name="searchButton"
/>
</span>
同一组件中的函数如下所示:
toggleSearchbar(event){
const eventType = event.type;
if(this.state.showSearch && this.props.q && length(this.props.q) > 0){
this.toggleSearching();
}else{
console.log("state after", this.state.showSearch) //false
this.setState({showSearch:!this.state.showSearch},function (event) {
console.log("state after", this.state.showSearch) //false
})
}
}
执行后,状态仍为false
事件
this.setState({showSearch:!this.state.showSearch},function (event) {
console.log("state after", this.state.showSearch) //false
})
但是,如果我使用onClick
代替onMouseDown
答案 0 :(得分:0)
试
this.setState(prev => ({showSearch: !prev.showSearch}), function(){.....})
而不是
this.setState({showSearch:!this.state.showSearch},function (event) {
console.log("state after", this.state.showSearch) //false
})