【问题标题】:React event handler is not called using jquery val() method不使用 jquery val() 方法调用 React 事件处理程序
【发布时间】:2015-09-15 23:16:31
【问题描述】:

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

下面是一个带有输入字段的简单反应组件。 每当值更改时,就会触发 onChange 事件处理程序并 value 设置为组件的状态。

  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 函数调用处理程序?

【问题讨论】:

  • .val() 从不触发更改事件(反应或其他)。此外,您应该找到一种无需使用 jQuery 或 dom 即可与组件进行通信的方法。
  • 当你试图让 React 和 jQuery 插件很好地协同工作时,说起来容易做起来难。
  • 将近三年后,这个问题仍然没有答案:(。stackoverflow.com/questions/49783314/…

标签: jquery event-handling reactjs


【解决方案1】:

你需要:

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.制作一个函数来处理它,它使用你的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 让我天真地兴奋!)

【讨论】:

    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 2013-12-29
    相关资源
    最近更新 更多