我在 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
处理程序的情况下为表单字段提供了一个props。这将呈现只读字段。如果字段应该是可变的,请使用defaultValue
. 否则,设置onChange
或readOnly
。检查 的渲染方法RecipeEditor
。
这是有道理的,但我不想要一个onChange
事件,我会用它ref
来获取提交时的值。它显然不是只读字段,因此我尝试将其更改为具有默认值。
<input type="text" ref="_name" defaultValue={this.props.recipe.name} />
这更接近我正在寻找的行为,但现在这仅在安装控件时设置配方,并且在选择新配方时不再更新。
该解决方案是否在每个设置状态的输入字段上都有一个处理程序,然后在提交时获取所有状态并更新配方?