原生js触发react change事件

作者: zengde 分类: 笔记 发布时间: 2021-08-17 03:13
var input=document.querySelector('input[placeholder="输入标题"]');

//For React 16 and React >=15.6

var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
nativeInputValueSetter.call(input, 'react 16 value');

var ev2 = new Event('input', { bubbles: true});
input.dispatchEvent(ev2);


//Outdated answer only for React <=15.5
var ev = new Event('input', { bubbles: true});
ev.simulated = true;
element.value = 'Something new';
element.dispatchEvent(ev);

如果是textarea需要使用HTMLTextAreaElement

来源:https://stackoverflow.com/questions/23892547/what-is-the-best-way-to-trigger-onchange-event-in-react-js/46012210