如何使用jquery val()方法调用React处理程序?

以下是带有输入字段的简单react组件。
每当值更改时,都会触发onChange事件处理程序,并
值设置为组件的状态。

  var Hello = React.createClass({

   getInitialState: function(){
     return {
        val: this.props.defVal || ""
     };
   },
   onChange: function(event){

    var newVal = event.target.value;
    console.log("changed", newVal);
    this.setState({val: newVal});

   },
   render: function() {
     return <div>
     <input id = "asd" className = "asd" value = {this.state.val} onChange = {this.onChange}/>
     Hello {this.props.name}</div>;
   }

  });

  React.render(<Hello name="World" />, document.getElementById('container'));


但是,当我使用jquery val方法时,不会触发onChange处理程序。
就像$('#asd')。val(“ asd”);

有没有一种方法可以使用jQuery val函数调用处理程序?

最佳答案

你需要:

1.在输入项目上设置ref,例如:

<input id="asd" className="asd" value={this.state.val}
ref={(myInput) => { this.myInput = myInput; }/>


...现在您可以参考this.myInput.value

比你能

2.使用其他事件运行任意代码,例如onBlur:

<input id="asd" className="asd" value={this.state.val}
ref={(myInput) => { this.myInput = myInput; }
onBlur={this.onBlur.bind(this)} />


(或更新的ES6语法相同)

...和:

3.make一个函数来处理它,它使用您的ref

onBlur(e) {
    var newVal = this.myInput.value; // uses the ref
    console.log("changed", newVal);
    this.setState({val: newVal});
}


注意:

与我在非特定于响应的页面上阅读的内容相反,您不能执行以下操作:

$('#asd').val("asd").change();


...
(至少有一个这样的SO answer让我天真的兴奋!)

07-24 09:43
查看更多