2017-03-03 94 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)