2017-03-03 92 views
1

我有一个React/Redux应用程序,并试图找出为受控输入字段构建适当的onChange事件的最佳方法。 React onChange在onInput上触发,所以我做了一个onBlur事件,只有当用户离开该字段时才会触发。我认为实现我的“onChange”代码的唯一方法是将输入值设置为React状态。然后,我可以将旧状态与来自Redux商店的新状态进行比较。但是我不认为这是一个理想的解决方案,因为这个值必须存储在React状态和Redux存储中。有没有一种方法可以为组件实现正确的onChange,而只有存储在Redux存储中的值?如何为受控React组件创建正确的onChange事件

/************Parent component************/ 
const mapStateToProps = (state) => { 
    const fieldName = 'fieldName'; 
    const fieldData = formFieldSelector(fieldName)(state); 

    return { 
     fieldName, 
     label: 'fieldName', 
     value: fieldData.value 
    } 
}; 

const mapDispatchToProps = (dispatch) => ({ 
    onChangeEvent(fieldName, value) { 
     dispatch(updateFieldValue(...)) 
    }, 
    onBlurEvent(fieldName, value) { 
     dispatch(validateFormField(...) 
    }, 
}); 

const MyFieldInput = connect(
    mapStateToProps, 
    mapDispatchToProps 
)(GenericInput); 

/************Child Component************/ 
export default class GenericInput extends React.Component { 

    constructor(props) { 
     super(props); 

     this.state = { 
      value: '' 
     }; 
    } 

    handleOnBlur (e) { 
     const value = e.target.value; 

     if(this.props.onBlurEvent && (value !== this.state.value)) { 
      this.props.onBlurEvent(this.props.fieldName, value) 
     } 

     this.setState({value}); 
    } 

    render() { 
     const { 
      fieldName, 
      label = '', 
      value = '', 
      inputType = 'text', 
      onChangeEvent, 
      onBlurEvent, 
     } = this.props; 
     const onChange = onChangeEvent ? (e) => onChangeEvent(fieldName, e.target.value) : function() {}; 

     return (
      <div> 
       <label>{label} 
        <input name={fieldName} type={inputType} value={value} onChange={onChange} onBlur={this.handleOnBlur.bind(this)} /> 
       </label> 
      </div> 
     ) 
    } 
} 

回答

0

删除onChange事件代码并使用ref分配onBlur的输入值。

所以你的输入应该是这样的:

<input name={fieldName} type={inputType} value={value} ref="fieldRef" onBlur={this.handleOnBlur.bind(this)} /> 

而且你会在handleOnBlur传递值如下:

this.props.onBlurEvent(this.props.fieldName, this.refs.fieldRef.value)