【发布时间】: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