zoukankan      html  css  js  c++  java
  • 在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库会覆盖输入值设置器,但是我们可以直接在inputas上下文中调用该函数。

    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元素,你应该使用prototypeHTMLTextAreaElement类。

    仅适用于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);
  • 相关阅读:
    unreal-python-howtos
    vscode plugin development
    [uva] 1671 History of Languages
    [codeup] 1128 出租车费
    [codeup] 1126 看电视
    Ubuntu 16.04 + ROS Kinetic 机器人操作系统学习镜像分享与使用安装说明
    (二)ROS系统架构及概念 ROS Architecture and Concepts 以Kinetic为主更新 附课件PPT
    ROS新功能包PlotJuggler绘图
    Winform DevExpress控件库(三) 使用NavBarControl控件定制导航栏
    数据意识崛起,从企业应用看BI软件的未来发展
  • 原文地址:https://www.cnblogs.com/jcz1206/p/14785221.html
Copyright © 2011-2022 走看看