ReactTestUtils.Simulate 无法通过 addEventListener 触发事件绑定? [英] ReactTestUtils.Simulate can't trigger event bind by addEventListener?

查看:34
本文介绍了ReactTestUtils.Simulate 无法通过 addEventListener 触发事件绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例如下:

http://jsfiddle.net/hulufei/twr4thuh/7/

在虚拟 dom(如第 18 行)中绑定 onClick 时它才起作用,但是如果我注释第 18 行并注释掉第 8 行以使用 addEventListener 绑定点击,它失败.

It just worked when bind onClick in virtual dom(like line 18), but If I comment line 18 and comment off line 8 to bind click with addEventListener, it failed.

那有什么问题?

推荐答案

TestUtils 在 react 的合成事件系统中触发事件,所以 addEventListener 监听的原生事件永远不会被触发.您将需要在测试中的元素上使用本机 click 方法:

TestUtils triggers events within react's synthetic event system, so the native event that addEventListener listens for is never going to be triggered. You will need to use the native click method on the element in your test:

    var events = Events();
    ReactTestUtils.renderIntoDocument(events);
    events.refs.button.getDOMNode().click();

    events.state.event.should.equal('click');

此外,您在 addEventListener 定义中拼错了 clickHandler.

Additionally, you've misspelled clickHandler in your addEventListener definition.

jsfiddle

您还可以通过重用 prop 定义来简化添加事件侦听器的过程:

You can also simplify adding your event listener by reusing your prop definition:

componentDidMount: function () {
    this.refs.button.getDOMNode().addEventListener('click', this.clickHandler);
},

注意:

为什么要使用 addEventListener 而不是仅仅为按钮传递一个 onClick 属性?除非有特别的和充分的理由,否则我建议在处理事件时以反应方式做事以保持理智:)

Is there a reason why you want to use addEventListener instead of just passing an onClick attribute for your button? Unless there's a specific and good reason otherwise, i'd suggest doing things the react way when handling events for sanity :)

我最初提到我不知道TestUtils的SimulateNative.click 没有触发事件.我认为它会是错误的,因为它会在反应甚至系统中模拟本机点击事件.@thilo 为我指明了正确的方向 :)

I originally mentioned that I did not know what TestUtils' SimulateNative.click did not trigger the event. I was wrong in thinking that it ever would since it would be simulating a native click event within the react even system. @thilo pointed me in the right direction :)

这篇关于ReactTestUtils.Simulate 无法通过 addEventListener 触发事件绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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