Sea*_*ean 5 javascript reactjs
给定具有受控输入的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
}
}
Run Code Online (Sandbox Code Playgroud)
然后你只需要将状态移动到子组件,而不是props.inputValue直接渲染.基本上你只是搬到handleChange孩子身边.
从设定的初始值props.inputValue中getInitialState,然后确保在更新子状态componentWillReceiveProps.