react初探-e.target为null.md

238 阅读1分钟

今天在使用antdinput组件和mobx做一个很简单的功能,获取input中的输入内容,然后传给后端做查询,可偏偏就遇到奇奇怪怪的坑~

删减后的代码大概长这样

  import store from './store'

  class SearchForm extends Component {

  handleSearchInput = e => {
    console.log(e.target.value)
  }
    render() {
      return(
        <Input.Search
          placeholder="支持标题、内容模糊查询"
          value={store.keyword}
          enterButton
          onChange={this.handleSearchInput}
        />
      )
    }
  }
  

可以说是非常非常简单常见的需求了,在输入的事件中获取输入框的内容。可是当我输入内容时,控制台报错了: Warning:Thissyntheticeventisreusedforperformancereasons.Ifyoureseeingthis,youreaccessingthepropertytargetonareleased/nullifiedsyntheticevent.Thisissettonull.Ifyoumustkeeptheoriginalsyntheticeventaround,useevent.persist().Seehttps://fb.me/reacteventpoolingformoreinformation.\color{red}{Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property `target` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist(). See https://fb.me/react-event-pooling for more information.}

此时e.target的值也为null

这就让我有点懵了,在仔细阅读报错信息后找到了一丝线索use event.persist()(所以说遇到报错不要慌,冷静分析报错信息~~) 然后去网上搜素了一下资料,发现原来官网上就有说明~~

注意: 如果你想异步访问事件属性,你需在事件上调用 event.persist(),此方法会从池中移除合成事件,允许用户代码保留对事件的引用。

加上方法后的代码

  import store from './store'

  class SearchForm extends Component {

  handleSearchInput = e => {
    e.persist()
    console.log(e.target.value)
  }
    render() {
      return(
        <Input.Search
          placeholder="支持标题、内容模糊查询"
          value={store.keyword}
          enterButton
          onChange={this.handleSearchInput}
        />
      )
    }
  }
  

完事~