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

时间:2017-01-17 13:58:43

标签: reactjs

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 个答案:

答案 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
      })