簡體   English   中英

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

[英]React: Controlling input value with both props and state

給定具有受控輸入的React組件,我希望能夠:

  1. 設置父項狀態的輸入值
  2. 允許用戶將輸入更改為任何值
  3. 僅在用戶提交並輸入通過驗證后才更新父級的狀態。

我可以使用下面的代碼片段完成1和2,但由於值通過props進入ChildComponent,我不確定如何在更改父項的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移動到孩子handleChange

getInitialState設置props.inputValue的初始值,然后確保更新componentWillReceiveProps的子狀態。

不推薦使用componentWillReceiveProps

資料來源: https//reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops

此生命周期之前名為componentWillReceiveProps。 該名稱將繼續有效,直到版本17.使用rename-unsafe-lifecycles codemod自動更新組件。

使用這樣的東西代替:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM