2016-11-24 86 views
9

我在學習如何實現React表單(ES6語法),並將每個字段的onChange事件傳遞給負責更新狀態的控制器父組件。這適用於標準html元素,但是我正在嘗試使用預先封裝的Datepicker(https://www.npmjs.com/package/react-bootstrap-date-picker)作爲日期字段,並且無法以相同的方式將事件重新傳遞迴父級。有沒有簡單的方法來解決這個問題?React子組件更新狀態的onChange事件

控制器組件

class Parent extends React.Component { 
    constructor (props) { 
     super(props); 
     this.state = {job: ''} 
    } 

    setJobState(event) { 
     var field = event.target.name; 
     var value = event.target.value; 
     this.state.job[field] = value; 
     this.setState({job: this.state.job}); 
    } 


    render() { 
     return <Child onChange={this.setJobState.bind(this)} /> 
    } 
} 

輔元件

class Child extends React.Component { 
    constructor (props) { 
     super(props); 

    } 

    render() { 
     <form> 
     <input type="text" name="jobNumber" onChange={this.props.onChange} /> 
     <DatePicker name="dateCmmenced" onChange={this.props.onChange} /> 
     </form> 
    } 
} 
+0

看起來像你正確綁定'onChange'處理程序,但'DatePicker'的'onChange'處理程序用兩個參數調用:'v alue'和'formattedValue'(見這裏:https://github.com/pushtell/react-bootstrap-date-picker#datepicker-)。在你的'Child'組件中,爲兩個'onChange'事件設置不同的處理程序,它們能夠處理參數的差異。 – forrert

+0

我會試一試,看看我能否得到它的工作。謝謝。 –

+0

還要小心如何更新狀態。 'this.state.job [field] = value'不是你應該如何更新你的狀態。總是通過調用'this.setState'來進行狀態更改。 – forrert

回答

11

DatePickeronChange處理程序不調用一個標準的瀏覽器change事件,但valueformattedValue作爲參數。我建議來登記您Child成分不同onChange處理程序變換相應的輸入域的事件:

控制器組件

class Parent extends React.Component { 
    constructor (props) { 
     super(props); 
     this.state = {} 
    } 

    onChange(field, value) { 
     // parent class change handler is always called with field name and value 
     this.setState({[field]: value}); 
    } 


    render() { 
     return <Child onChange={this.onChange.bind(this)} /> 
    } 
} 

輔元件

class Child extends React.Component { 
    constructor (props) { 
     super(props); 
    } 

    onFieldChange(event) { 
     // for a regular input field, read field name and value from the event 
     const fieldName = event.target.name; 
     const fieldValue = event.target.value; 
     this.props.onChange(fieldName, fieldValue); 
    } 

    onDateChange(dateValue) { 
     // for a date field, the value is passed into the change handler 
     this.props.onChange('dateCommenced', dateValue); 
    } 

    render() { 
     return <form> 
      <input type="text" name="jobNumber" onChange={this.onFieldChange.bind(this)} /> 
      <DatePicker onChange={this.onDateChange.bind(this)} /> 
     </form> 
    } 
}