reactjs – react中的onMouseDown事件不会触发状态更改但onClick
发布时间:2020-12-15 20:19:34 所属栏目:百科 来源:网络整理
导读: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.ty
|
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
})
}
}
执行后,国家仍然是错误的事件 this.setState({showSearch:!this.state.showSearch},function (event) {
console.log("state after",this.state.showSearch) //false
})
但是,如果我使用onClick而不是onMouseDown,它的工作正常 解决方法
尝试
this.setState(prev => ({showSearch: !prev.showSearch}),function(){.....})
代替 this.setState({showSearch:!this.state.showSearch},this.state.showSearch) //false
})
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
