React渲染输入的触发器更改事件(类型=范围) [英] Trigger change event for React rendered input (type=range)

查看:108
本文介绍了React渲染输入的触发器更改事件(类型=范围)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

react:^ 15.4.2

"react": "^15.4.2"

我无法从jquery为使用React呈现的输入触发更改事件。
我需要为端到端测试做这件事。

I am having trouble triggering the change event from jquery for an input rendered with React. I need to do this for some end to end testing.

这里是一个完整展示的沙箱: https://codesandbox.io/s/pp1k1kq3om
已加载jquery。

here's a sandbox as a full showcase: https://codesandbox.io/s/pp1k1kq3om with jquery already loaded.

如果你在控制台中运行:$('#reactSlider')。val(50).change(),你会注意到没有调用更改处理程序。

If you run : $('#reactSlider').val(50).change() in the console, you'll notice that the change handler isn't called.

在上面的沙箱中还有一个纯html滑块用于比较,一个按预期工作(调用更改函数)。

In the sandbox above there's also a pure html slider for comparison, that one works as expected (change function is called).

也试图发送一个新的这样的事件:

also tried to dispatch a new event like this:

var event = new Event('change')
var target = $('#reactSlider')[0];
target.dispatchEvent(event);

上述情况也不起作用(并且可以在纯html滑块上工作)。

The above doesn't work either (and does work on the pure html slider).

import React from "react";
import { render } from "react-dom";

const changeHandler = event => {
  alert(`react slider changed:${event.target.value}`);
};

const App = () => (
  <div>
    <label htmlFor="reactSlider">react-slider</label>
    <input
      id="reactSlider"
      type="range"
      onChange={changeHandler}
      min={10}
      max={100}
      step={10}
      value={20}
    />
    <p>run in the console: $('#reactSlider').val(50).change()</p>
    <br />
    <br />
    <p>Notice that for the React slider, the change event is not triggered.</p>
  </div>
);

render(<App />, document.getElementById("root"));


推荐答案

好的,所以我发现了一种解决方法。
看起来onInput事件可以被触发就好了。在输入类型='范围'的情况下,输入事件在与更改相同的情况下被触发,因此我能够切换它。

Ok, so I've found sort of a workaround. it looks like the onInput event can be triggered just fine. In the case of input type='range' the "input" event is triggered in the same situation as the "change" is so I was able to switch it.

解决方法是:使用onInput而不是onChange并像这样触发它:

Workaround would be: use onInput instead of onChange and trigger it like this:

function triggerChange(selector,evt) {
    let ev = new Event(evt, { bubbles: true });
        let el = $(selector)[0]

        el.dispatchEvent(ev);
  };
triggerChange('#reactSlider','input');

这篇关于React渲染输入的触发器更改事件(类型=范围)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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