【问题标题】:Initializing an input field with props value in react在反应中使用道具值初始化输入字段
【发布时间】:2018-11-05 18:13:50
【问题描述】:

我有一个子组件,它有一个文本输入字段,其值应该使用来自父组件 (this.props.index) 的道具进行初始化。

这应该是受控输入,因为我希望能够存储输入的文本。

现在,如果我将值设置为 state 的属性,那么无论何时重新渲染组件,它都不会更新,因为 setState 永远不会被调用:

<input type={"text"} placeholder={"Index"} className={"form-control"}
                       value={this.state.index} onChange={this.updateStudentIndex}/>

另一方面,如果我将值设置为道具的属性,它是固定的,无法进行更改:

<input type={"text"} placeholder={"Index"} className={"form-control"}
                       value={this.props.index} onChange={this.updateStudentIndex}/>

我怎样才能使用this.props.index 初始化状态,并且仍然能够跟踪输入值this.state.index 的变化?

编辑:初始化应该在异步模式下完成,即当我单击父组件中的按钮时。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我认为default values 在这里可能会有所帮助。

    【讨论】:

    • 不,这没有帮助。我收到以下错误:EditStudentDetails contains an input of type text with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both).
    【解决方案2】:

    如果您熟悉The Component Lifecycle,请使用componentWillReceiveProps,然后在此处设置新的state

    componentWillReceiveProps(nextProps) {
       if(this.props.index !== nextProps.index) {
         this.setState({index: nextProps.index})
       }
    }
    

    你可以在state 中保存你的值,所以componentWillMount 将你的state.index 设置为props.index

    【讨论】:

    • componentWillUpdate(){ this.setState({index: this.props.index}) } 导致最大更新深度超出异常
    • componentWillReceiveProps 不是很快就会被弃用,不应该使用吗?
    【解决方案3】:

    constructor 中读取props 的值并将其设置为state,这样您将获得props.index 并维护state 后缀中的更改。在onChange 事件处理程序中,您可以使用当前值更新index

    class Child extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          index: props.index
        }
      }
      ...
      render() {
        const { index } = this.state;
        ...
      }
    }
    

    希望这会有所帮助!

    【讨论】:

    • 很遗憾没有,因为在第一次创建子组件时调用了构造函数,但是我需要异步初始化,即当我单击按钮时,输入字段被初始化。
    • 哦,但你没有在问题中提到asynchronously initializing,也没有提到button :) ...
    • 真的,对不起。您还有其他解决方案吗?
    • 不,您能否分享更多详细信息,父子组件的关联方式以及初始化子组件的时间。如果可能的话,分享一些代码。
    • 我找到了一个解决方案,它在于不受控制的组件。
    【解决方案4】:

    找到解决方案,这不应该用受控组件来完成,而是uncontrolled components

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 2018-07-28
      • 2018-08-31
      • 2022-11-26
      • 1970-01-01
      相关资源
      最近更新 更多