奇怪为什么以下方法不起作用:
const onChange = e => {
console.log(e.target.value)
setEmails(prevEmails => ({
...prevEmails,
reports: e.target.value
}))
}
事件'e'变量console.logs,但是在setEmails中使用时,它说找不到null值? 确切的错误:
Cannot read property 'value' of null
我在这里想念什么?
答案 0 :(得分:3)
您应该将值保存到另一个变量,或使用e.persist()
:
const onChange = e => {
console.log(e.target.value);
let myValue = e.target.value;
setEmails(prevEmails => ({
...prevEmails,
reports: myValue
}))
}
这是因为出于性能原因,在React中使用synthetic events。在文档的 event pooling 部分中:
SyntheticEvent
已合并。这意味着在调用事件回调之后,SyntheticEvent
对象将被重用,并且所有属性都将无效。这是出于性能原因。因此,您不能以异步方式访问事件。