React:使用 props 和 state 控制输入值

React: Controlling input value with both props and state

给定一个具有受控输入的 React 组件,我希望能够:

  1. 设置父状态的输入值
  2. 允许用户将输入更改为任何值
  3. 仅在用户提交并输入通过验证后更新父级状态。

我可以使用下面的代码片段完成 1 和 2,但是由于值是通过 props 进入 ChildComponent 的,所以我不确定如何更改输入值 without更改 myInput 在父项上的值。

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

那么你只需要将状态移动到子组件,而不是直接从 props.inputValue 渲染。基本上,您只需将 handleChange 移至子项即可。

getInitialState中设置props.inputValue的初始值,然后确保在componentWillReceiveProps中更新子状态。

componentWillReceiveProps 已弃用

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

This lifecycle was previously named componentWillReceiveProps. That name will continue to work until version 17. Use the rename-unsafe-lifecycles codemod to automatically update your components.

改用这样的东西:

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