[英]React: Controlling input value with both props and state
給定具有受控輸入的React組件,我希望能夠:
我可以使用下面的代碼片段完成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
的子狀態。
資料來源: 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.