一.问题:使用antDesign的<input>组件onchange事件想要获取输入的值,发现conosle.log(e)中target值为null,但是e.target.value却可以获取到输入的值
代码:
<Input
value=''
placeholder="搜索姓名"
onChange={this.handleCurPrinciple}
/>
handleCurPrinciple=(e)=>{
console.log("e",e)
console.log("e.target", e.target)
}
結果 :e

e.target

其中e打印出的target值为null
二.原因分析:
打印event对象,event.target的值为null ,是react的事件机制导致的相关问题,需要使用event.persist() 异步获取。
三.解决方法:
在获取target之前调用event.persist()
handleCurPrinciple=(e)=>{
e.persist()
console.log("e",e)
console.log("e.target",e.target)
}
结果

在React应用中,使用antDesign的<Input/>组件时遇到onchange事件的event.target值为null的问题。这实际上是React的事件机制导致的,React通过合成事件(SyntheticEvent)来统一浏览器事件。为了解决这个问题,需要在访问event.target之前调用event.persist()来阻止事件池回收事件对象。通过在handleCurPrinciple方法中加入e.persist(),可以正确地打印出e.target.value,从而获取到输入框的值。

8858

被折叠的 条评论
为什么被折叠?



