onChange callback not firing in React component

前端 未结 1 552
春和景丽
春和景丽 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 (
          
    ); } }

    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 (
          
    提交评论

提交回复
热议问题