【发布时间】:2017-03-25 06:26:02
【问题描述】:
为了简单起见,我在 Redux 应用程序中有以下用于食谱的组件,目前只有一个名称。
class RecipeEditor extends Component {
onSubmit = (e) => {
e.preventDefault()
this.props.updateRecipe(this.props.recipe, { name: this.refs._name.value })
}
render = () => {
if (!this.props.recipe) {
return <div />
}
return (
<div>
<form onSubmit={this.onSubmit}>
<label>Name: </label>
<input type="text" ref="_name" value={this.props.recipe.name} />
<input type="submit" value="save" />
</form>
</div>)
}
static propTypes = {
recipe: React.PropTypes.shape({
name: React.PropTypes.string.isRequired
})
}
}
这给了我一个带有无法编辑的文本框的编辑器。控制台中也有警告:
警告:表单 propType 失败:您向表单提供了
value道具 没有onChange处理程序的字段。这将呈现只读 场地。如果该字段应该是可变的,请使用defaultValue。否则, 设置onChange或readOnly。检查渲染方法RecipeEditor.
这是有道理的,但我不想要onChange 事件,我将使用ref 来获取提交时的值。这显然不是只读字段,所以我尝试将其更改为具有默认值。
<input type="text" ref="_name" defaultValue={this.props.recipe.name} />
这更接近我正在寻找的行为,但现在这只在安装控件时设置配方,并且在选择新配方时不再更新。
解决方案是否在每个输入字段上都有一个处理程序来设置状态,然后在提交时获取所有状态并更新配方?
【问题讨论】: