简体   繁体   English

用React触发onchange事件-componentDidMount不起作用

[英]Trigger onchange event with React - componentDidMount not working

I have a page with a bunch of react generated dropdowns that do specific actions when an option is selected. 我有一个页面,其中包含一堆反应生成的下拉列表,这些下拉列表在选择选项时会执行特定的操作。 They work fine using their own 'onChange' methods, but I want to find a way to trigger them from an outside function too. 它们使用自己的“ onChange”方法可以正常工作,但我也想找到一种从外部函数触发它们的方法。 I tried doing: 我试着做:

var Dropdown = React.createClass({
  getInitialState: function () {
    return{firstTime: true};
  },
  onChange: function(event){
    if (this.state.firstTime===true) {
      if (typeof this.props.onChange === 'function') {
        this.props.onChange(event.target, true);
    }
  }
  else {
    if (typeof this.props.onChange === 'function') {
        this.props.onChange(event.target, false);
    }
  }
    this.setState({firstTime: false});
  },
  componentDidMount: function() {
    var dropdown = this.refs.dropdown;
    dropdown.addEventListener('change', this.onChange, false);
  },
  render: function() {
    return (
      <select className={this.props.className} onChange={this.onChange} ref='dropdown'>
        {this.props.options.map(function(option){
          return (
              <Option value={option.value} key={option.value}>{option.label}</Option>
            );
        })}
    </select>
    );
  }
});

And then calling document.querySelector("select.header").onchange; 然后调用document.querySelector(“ select.header”)。onchange; just in the console of my page, and nothing happens. 只是在我页面的控制台中,什么也没有发生。 Thoughts? 思考?

Found an answer. 找到了答案。 For some reason I was able to trigger it with jQuery $("select.header").change(); 由于某种原因,我能够使用jQuery $(“ select.header”)。change();触发它。 but not document.querySelector("select.header").onchange(); 但不是document.querySelector(“ select.header”)。onchange();

No idea why, but at least I found a solution. 不知道为什么,但至少我找到了解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM