2016-11-24 84 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> 
    } 
}