onChange event for React child component to update state

前端 未结 2 1363
夕颜
夕颜 2020-12-08 10:53

I\'m trying to learn how to implement a React form (ES6 syntax) and pass the onChange events for each field up to a controller parent component which is responsible for upda

2条回答
  •  没有蜡笔的小新
    2020-12-08 11:46

    The onChange handler for the DatePicker is not called with a standard browser change event, but with value and formattedValue as arguments. I would recommend to register different onChange handlers in your Child component that transform the respective input field's event:

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

提交回复
热议问题