【发布时间】:2015-05-12 03:19:06
【问题描述】:
给定一个带有受控输入的 React 组件,我希望能够:
- 从父状态设置输入值
- 允许用户将输入更改为任何值
- 仅在用户提交且输入通过验证后更新父级的状态。
我可以使用下面的 sn-p 完成 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
}
}
【问题讨论】:
标签: javascript reactjs