gpt4 book ai didi

javascript - react : Controlling input value with both props and state

转载 作者:搜寻专家 更新时间:2023-11-01 05:22:17 24 4
gpt4 key购买 nike

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

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

我可以使用下面的代码片段完成 1 和 2,但是由于值是通过 props 进入 ChildComponent 的,所以我不确定如何更改输入值而不更改 myInput 的值在 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
}
}

最佳答案

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

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

关于javascript - react : Controlling input value with both props and state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30181198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com