onChange callback not firing in React component

前端 未结 1 557
春和景丽
春和景丽 2021-01-19 16:54

My onChange() function does not run unless I use jQuery for some reason. The reason why I have to add the onChange listener in componentDidMo

相关标签:
1条回答
  • 2021-01-19 17:20

    The problem is that the plugin is emitting a custom change event. React's event system doesn't recognize custom events (not sure why).

    In this case a manual change listener is the right solution. The way you improve this is by abstracting the select element to an 'atom'.

    class Select extends React.Component {
      static propTypes = {
        value: React.PropTypes.string,
        options: React.PropTypes.arrayOf(
          React.PropTypes.shape({
            text: React.PropTypes.string.isRequired,
            value: React.PropTypes.string.isRequired,
          })
        ).isRequired
      };
      constructor() {
        super();
        this.onChange = this.onChange.bind(this);
      }
    
      onChange(e) {
        this.props.onChange(e.target.value);
      }
    
      componentDidMount() {
        let select = this.refs.select;
        select.addEventListener('change', this.onChange, false);
      }
    
      componentWillUnmount(){
        let select = this.refs.select;
        select.removeEventListener('change', this.onChange, false);  
      }
    
      render() {
        let classes = 'input-field col s10 offset-s1 l3';
    
        return (
          <div className={classes}>
            <select ref="select" value={this.props.value}>
              {this.props.options.map((x) => {
                return <option key={x.value} value={x.value}>{x.text}</option>;
              })}
            </select>
          </div>
        );
      }
    }
    

    You can then use this in InspectionMode or anywhere else in your UI.

    class InspectionMode extends React.Component {
      constructor(props) {
        super(props);
        this.onChange = this.onChange.bind(this);
        this.value = 'selected';
        this.state = { inspectionTime: 0 };
      }
    
      onChange(inspectionTime) {
        this.setState({ inspectionTime });
      }
    
      render() {
        return (
          <div>
            <Select 
              value={this.state.inspectionTime}
              onChange={this.onChange}
              options={[
                {value: '0', text: 'None'},
                {value: '5', text: '5 seconds'},
                {value: '10', text: '10 seconds'},
                {value: '15', text: '15 seconds'},
              ]}
            />
            <label>Inspection Time</label>
          </div>
        );
      }
    }
    
    0 讨论(0)
提交回复
热议问题