react初探-e.target为null

本文介绍了一个关于React中合成事件的常见问题,即在处理input输入事件时,事件对象的target属性在某些情况下返回null。文章详细解释了这一问题的原因,并提供了解决方案,即使用event.persist()方法来确保事件对象的持久性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在使用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}
        />
      )
    }
  }
  

可以说是非常非常简单常见的需求了,在输入的事件中获取输入框的内容。可是当我输入内容时,控制台报错了:
W a r n i n g : T h i s s y n t h e t i c e v e n t i s r e u s e d f o r p e r f o r m a n c e r e a s o n s . I f y o u ′ r e s e e i n g t h i s , y o u ′ r e a c c e s s i n g t h e p r o p e r t y ‘ t a r g e t ‘ o n a r e l e a s e d / n u l l i f i e d s y n t h e t i c e v e n t . T h i s i s s e t t o n u l l . I f y o u m u s t k e e p t h e o r i g i n a l s y n t h e t i c e v e n t a r o u n d , u s e e v e n t . p e r s i s t ( ) . S e e h t t p s : / / f b . m e / r e a c t − e v e n t − p o o l i n g f o r m o r e i n f o r m a t i o n . \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.} Warning:Thissyntheticeventisreusedforperformancereasons.Ifyoureseeingthis,youreaccessingthepropertytargetonareleased/nullifiedsyntheticevent.Thisissettonull.Ifyoumustkeeptheoriginalsyntheticeventaround,useevent.persist().Seehttps://fb.me/reacteventpoolingformoreinformation.

此时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}
        />
      )
    }
  }
  

完事~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值