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

Sea*_*ean 5 javascript reactjs

给定具有受控输入的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
    }
}
Run Code Online (Sandbox Code Playgroud)

Jom*_*rio 8

然后你只需要将状态移动到子组件,而不是props.inputValue直接渲染.基本上你只是搬到handleChange孩子身边.

从设定的初始值props.inputValuegetInitialState,然后确保在更新子状态componentWillReceiveProps.

  • 虽然保持应用程序状态集中是件好事,但文本字段的值不是真正的应用程序状态,而是视图状态.这确实属于组件内部.一个好的经验法则是,如果在卸载组件时您的状态不再相关,则它应该是该组件的本地状态. (3认同)