React select元素onChange不会触发

时间:2017-04-25 17:52:04

标签: javascript reactjs events

我正在创建一个可以在许多表单上使用的select React组件。出于某种原因,onChange事件未被触发。

这是元素(省略了proptypes和默认道具):

var Select = React.createClass ({
  getInitialState() {
    return {
      value: null,
    }
  },

  componentWillReceiveProps(props) {
    if (props.defaultValue) {
      this.setState({value: props.defaultValue})
    }
  },

  render() {
    var formClass = this.props.error ? "form-group has-error" : "form-group"
    var validationMsg = this.props.error ? <span className="help-block"><small>{this.props.error}</small></span> : null

    var labelClass = 'control-label col-md-' + this.props.labelWidth
    var inputWidth = 12 - this.props.labelWidth
    var widthClass = 'col-md-' + inputWidth

    return (
      <div className={formClass}>
        <label className={labelClass}>{this.props.label}</label>
        <div className={widthClass}>
          <div className="input-wrapper">
            <select ref="mySelect" className={this.props.className}
                    multiple={this.props.multiple}
                    value={this.state.value}
                    onChange={this._onchange}>
              {
                this.props.options.map((option, index) => {
                  return <Option key={index} value={option.value} text={option.text} />
                })
              }
            </select>
          </div>
          {validationMsg}
        </div>
      </div>
    )
  },

  getValue() {
    if (this.props.multiple) {
      var selected = [];
      for ( var i = 0; i < this.refs["mySelect"].selectedOptions.length; i++) {
        selected.push(this.refs["mySelect"].selectedOptions[i].value)
      }
      return selected
    }
    return this.state.value
  },

  _onchange(event) {
    console.log('hi')
    this.setState({value: event.target.value})
  }
})

我在函数中添加了带有硬编码字符串的console.log语句,它永远不会打印到控制台。

我尝试过的事情:

onchange={this._onchange}

onChange={this._onchange.bind(this)}

onChange={(evt) => this._onchange(evt)}

onChange={function(e) {console.log('test')}}

如果重要,这里是Option组件:

var Option = React.createClass ({
  propTypes: {
    value: React.PropTypes.any.isRequired,
    text: React.PropTypes.string.isRequired,
  },

  render() {
    return (<option value={this.props.value}>{this.props.text}</option>)
  }
})

我看过的问题:

React select onChange is not working

My onChange not working with react

OnChange event using React JS for drop down

React input onChange won't fire

https://jsfiddle.net/69z2wepo/9958/(它可以在这里工作!)

onChange callback not firing in React component

0 个答案:

没有答案