Trigger change event for React rendered input (type=range)

时间秒杀一切 提交于 2019-12-10 11:58:34

问题


"react": "^15.4.2"

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.

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

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

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);

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"));

回答1:


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.

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');


来源:https://stackoverflow.com/questions/49783314/trigger-change-event-for-react-rendered-input-type-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!