簡體   English   中英

用React觸發onchange事件-componentDidMount不起作用

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

我有一個頁面,其中包含一堆反應生成的下拉列表,這些下拉列表在選擇選項時會執行特定的操作。 它們使用自己的“ onChange”方法可以正常工作,但我也想找到一種從外部函數觸發它們的方法。 我試着做:

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

然后調用document.querySelector(“ select.header”)。onchange; 只是在我頁面的控制台中,什么也沒有發生。 思考?

找到了答案。 由於某種原因,我能夠使用jQuery $(“ select.header”)。change();觸發它。 但不是document.querySelector(“ select.header”)。onchange();

不知道為什么,但至少我找到了解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM