简体   繁体   中英

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. 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; 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(); but not document.querySelector("select.header").onchange();

No idea why, but at least I found a solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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