【问题标题】:React: Controlling input value with both props and stateReact:使用 props 和 state 控制输入值
【发布时间】:2015-05-12 03:19:06
【问题描述】:

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

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

我可以使用下面的 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


    【解决方案1】:

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

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

    【讨论】:

    • 这是有道理的。本着 Flux 的精神,我一直在尝试在顶级组件之外谨慎使用状态,并拥有单一的事实来源。我认为这是不同的,尽管考虑到输入的值实际上是组件本身的内部,直到用户提交。
    • @Sean 是的,我同意将状态集中在顶级组件中的原则。但在这种情况下,父母并不真正关心输入的当前值,而孩子确实需要跟踪它(用于验证目的)。
    • 虽然保持应用程序状态集中是好的,但文本字段的值并不是真正的应用程序状态,而是视图状态。这确实属于组件内部。一个好的经验法则是,如果您的状态在组件卸载时不再相关,则它应该是该组件的本地状态。
    【解决方案2】:

    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
                });
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-25
      • 2018-05-04
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 2015-03-15
      • 2017-09-24
      • 2018-05-12
      相关资源
      最近更新 更多