【问题标题】:defaultValue not updating on DOM re render in reactdefaultValue 未在 DOM 上更新重新渲染反应
【发布时间】:2017-08-14 13:49:37
【问题描述】:

我正在研究 react js,我有一个用户可以输入值的文本,所以我在其中使用了 defaultValue。这个值也会被外部事件改变。但是如果使用外部事件修改值,它不会反映在我的输入框中(直到我刷新页面)。但我输入了它正在更新的输入框的 value 字段。但用户不能编辑它。我怎样才能同时拥有这两种功能意味着用户也可以更新其他事件。 这是我的输入框

  <input type="text"  defaultValue={this.props.growth}  onBlur={(e) => this.props.growth(e.target.value)}></input>

编辑1: 我添加了 vivek 所说的功能,但现在文本框变得不可编辑

constructor(props){
       super(props);
       this.state ={
           modifedProgramGrowth: this.props.growth
       }
   }
updateGrowthValue(key){
        console.log("value",key)
        this.setState({growth:key})
}

<input type="text"  value={this.state.growth} onChange={(e) => this.updateGrowthValue.bind(e.target.value)} onBlur={(e) => this.props.growth(e.target.value)}></input>

【问题讨论】:

  • this.props.growth可以是这个组件的状态吗?
  • @VivekN: 但在那种情况下我不能让它可编辑
  • 为什么会这样,你可以将 defaultValue 作为 this.state.growth 和 onChange 你用 this.setState 更新你的状态,然后反应会导致重新渲染,你的输入框将开始有用户键入的值。
  • @VivekN 你说的是受控组件,它不使用defaultValue,而只是value
  • 使用受控输入,因此您将拥有一个 onChange 处理程序来在您键入时更新值,并且您还可以更新某些事件的状态,这也将被反映

标签: reactjs react-redux


【解决方案1】:

根据您编辑的问题,如果您已经在使用箭头函数,则无需使用 bind 为函数提供参数。改为

constructor(props){
       super(props);
       this.state ={
           modifedProgramGrowth: this.props.growth
       }
   }
updateGrowthValue(key){
        console.log("value",key)
        this.setState({growth:key})
}

<input type="text"  value={this.state.growth} onChange={(e) => this.updateGrowthValue(e.target.value)} onBlur={(e) => this.props.growth(e.target.value)}></input>

【讨论】:

  • 但是我的值没有被外部事件更新..:(这可能是因为我的构造函数只初始化一次吧?
【解决方案2】:

从shubham的回答中制作可编辑的文本框,我已将componentWillReceiveProps(nextProps)添加到我的代码中以解决问题

componentWillReceiveProps(nextProps)
{
        let {growth } =this.state;
       growth = nextProps.growth ;
        this.setState({growth })
}

【讨论】:

    猜你喜欢
    • 2020-10-06
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2020-02-17
    • 2015-08-09
    • 2023-03-22
    相关资源
    最近更新 更多