首页 文章

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

提问于
浏览
15

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

Controller Component

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)} />
    }
}

Child Component

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>
    }
}

1 回答

  • 27

    DatePickeronChange 处理程序未使用标准浏览器 change 事件调用,但使用 valueformattedValue 作为参数 . 我建议在 Child 组件中注册不同的 onChange 处理程序,以便转换相应的输入字段的事件:

    Controller Component

    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)} />
        }
    }
    

    Child Component

    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>
        }
    }
    

相关问题