react中的 onMouseDown 事件不会触发状态更改,但 onClick 会

IT技术 reactjs
2021-05-13 11:28:13

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

1个回答

尝试

this.setState(prev => ({showSearch: !prev.showSearch}), function(){.....})

代替

this.setState({showSearch:!this.state.showSearch},function (event) {
      console.log("state after", this.state.showSearch) //false
      })