为什么未在dispatchEvent上调用React事件处理程序? [英] Why React event handler is not called on dispatchEvent?

查看:138
本文介绍了为什么未在dispatchEvent上调用React事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆