Reaction: control the input value using both props and status

Given the React component with controlled input, I would like to be able to:

  • Set input value from parent state
  • Allow user to change input to any value
  • Update the parent state only after the user submits and validates the input.

I can execute 1 and 2 with the snippet below, but since the value appeared in ChildComponent through the details, I am not sure how to change the input value without changing the myInput value on the parent.

class ChildComponent extends React.Component
{
    render(){
        return <input type="text" value={this.props.inputValue} onChange={this.handleChange.bind(this)} />
    }  
    handleChange(e){
        this.props.onInputChange(e.target.value);
    }
    handleSubmit(){
        // do some validation here, it it passes...
        this.props.handleSubmit();
    }
}

class ParentComponent extends React.Component{
    constructor(){
      super();
      this.state = {myInput: ""};
    }
    render(){
        return <ChildComponent inputValue={this.state.myInput} onInputChange={this.handleChange.bind(this)} />
    }
    handleChange(newValue){
        this.setState({myInput: newValue});
    }
    handleSubmit(){
        // do something on the server
    }
}
+4
source share
2 answers

, props.inputValue. handleChange .

props.inputValue getInitialState, , componentWillReceiveProps.

+7

componentWillReceiveProps

: https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

componentWillReceiveProps. 17. Renode-unsafe-lifecycles codemod .

- :

componentDidUpdate(prevProps) {       
        if (this.props.yourObj != null && prevProps.yourObj !== this.props.yourObj) {
            this.setState({
                yourStateObj = this.props.yourObj
            });
        }
}
0

All Articles