React JS文本框模拟输入值更改
React JS
(或Vue
)文本框模拟输入值更改
代码
做成 jquery 扩展方法
jQuery.fn.valReact = function(text) {
if (!this.is(':focus')) this.focus();
let input = this[0];
if (!input) return;
let lastValue = input.value;
input.value = text;
let event = new Event('input', { bubbles: true });
// hack React15
event.simulated = true;
// hack React16 内部定义了descriptor拦截value,此处重置状态
let tracker = input._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
}
input.dispatchEvent(event);
}
使用:
$("#inputId").valReact('hello');
参考:
- What is the best way to trigger onchange event in react js
- Trigger simulated input value change for React 16
blog comments powered by Disqus