不使用jquery val()方法调用React事件处理程序 [英] React event handler is not called using jquery val() method

查看:82
本文介绍了不使用jquery val()方法调用React事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Below is a simple react component with input field. Whenever the value changes the onChange event handler is fired and value is set to state of the component.

  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");

However the onChange handler is not fired when i use jquery val method. Like $('#asd').val("asd");

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

Is there a way i can invoke the handler using jquery val function?

推荐答案

您需要:

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

1.Set a ref on the input item, like:

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

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

...now you can refer to this.myInput.value .

比你能

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

2.run arbitrary code using some other event, such as onBlur:

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

(或相同版本的更新的ES6语法)

(or newer ES6 syntax for the same)

...并且:

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

3.make a function to handle it, which uses your ref:

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

NB:

与我在非特定于反应的页面上阅读的内容相反,您不能这样做:

Contrary to what I've read on pages that aren't react-specific, you can't do:

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

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

... (There's at least one such SO answer that got me naively excited!)

这篇关于不使用jquery val()方法调用React事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆