React子组件的onChange事件更新状态

Han*_*man 21 javascript reactjs

我正在尝试学习如何实现React表单(ES6语法)并将每个字段的onChange事件传递给负责更新状态的控制器父组件.这适用于标准的html元素,但我正在尝试使用预先固定的Datepicker(https://www.npmjs.com/package/react-bootstrap-date-picker)作为日期字段,并且无法轻松传递事件以同样的方式回到父母那里.有一个简单的方法来解决这个问题吗?

控制器组件

   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)} />
    }
}
Run Code Online (Sandbox Code Playgroud)

子组件

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>
    }
}
Run Code Online (Sandbox Code Playgroud)

for*_*ert 39

不使用标准浏览器事件调用该onChange处理程序,而是使用和作为参数.我建议在组件中注册不同的处理程序,以转换相应的输入字段的事件:DatePickerchangevalueformattedValueonChangeChild

控制器组件

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)} />
    }
}
Run Code Online (Sandbox Code Playgroud)

子组件

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>
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 正是我一直在寻找的!1+ (4认同)