在React JS中应用的页面,如何使用javascript触发onchange
https://codingdict.com/questions/77442
https://codepen.io/catthr/pen/pddWzo
class NameForm extends React.Component { constructor(props) { super(props); this.state = {value: ''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({value: event.target.value}); } handleSubmit(event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); } } ReactDOM.render( <div><NameForm /> <NameForm /> </div>, document.getElementById('root') ); // doesn't work since v15.6.0 var ev = new Event('input', { bubbles: true}); document.querySelector('form:first-child input').value = 'Not working'; document.querySelector('form:first-child input').dispatchEvent(ev); var input = document.querySelector('form:last-child input'); 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);
对于React 16和React > = 15.6
设置.value=
器无法正常工作,因为React库会覆盖输入值设置器,但是我们可以直接在input
as上下文中调用该函数。
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);
对于textarea元素,你应该使用prototype
的HTMLTextAreaElement
类。
仅适用于React <= 15.5的过时答案
有了react-dom ^15.6.0
您可以使用simulated
标志事件对象的事件经过
var ev = new Event('input', { bubbles: true});
ev.simulated = true;
element.value = 'Something new';
element.dispatchEvent(ev);