为什么未在dispatchEvent上调用React事件处理程序? [英] Why React event handler is not called on dispatchEvent?
问题描述
在React组件中考虑以下输入元素:
Consider the following input element in a React component:
<input onChange={() => console.log('onChange')} ... />
在测试React组件时,我正在模拟用户更改输入值:
While testing the React component, I'm emulating user changing the input value:
input.value = newValue;
TestUtils.Simulate.change(input);
这将导致按预期记录'onChange'
.
但是,当直接调度'change'
事件时(我正在使用jsdom):
However, when the 'change'
event is dispatched directly (I'm using jsdom):
input.value = newValue;
input.dispatchEvent(new Event('change'));
未调用onChange
处理程序.
为什么?
我之所以使用dispatchEvent
而不是TestUtils.Simulate
是因为TestUtils.Simulate
不支持事件冒泡,而我组件的行为依赖于此.我想知道是否有一种方法可以在没有TestUtils.Simulate
的情况下测试事件?
My motivation to use dispatchEvent
rather than TestUtils.Simulate
is because TestUtils.Simulate
doesn't support event bubbling and my component's behavior relies on that. I wonder whether there is a way to test events without TestUtils.Simulate
?
推荐答案
React将其自己的事件系统与SyntheticEvents
一起使用(防止浏览器不兼容,并提供对事件的更多控制).
React uses its own events system with SyntheticEvents
(prevents browser incompatabilities and gives react more control of events).
正确使用TestUtils
会创建这样的事件,该事件将触发您的onChange
侦听器.
Using TestUtils
correctly creates such a event which will trigger your onChange
listener.
另一方面,dispatchEvent
函数将创建一个本机"浏览器事件.但是您拥有的事件处理程序是由react管理的,因此仅对SyntheticEvents
做出反应(徽章).
The dispatchEvent
function on the other hand will create a "native" browser event. But the event handler you have is managed by react and therefore only reacts (badumts) to reacts SyntheticEvents
.
您可以在此处阅读反应事件: https://facebook.github.io/react/docs/events.html
You can read up on react events here: https://facebook.github.io/react/docs/events.html
这篇关于为什么未在dispatchEvent上调用React事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!