我刚开始使用 React,一直停留在编辑表单上。我需要预填充输入,但也能够对其进行编辑。如果我设置 defaultValue,我就无法在输入元素上设置值。此时我可以输入输入,但我必须编辑两个字段(表单有两个字段)以保存两个值。我应该怎么做?
例子: 我有食谱名称和配料,我打开带有编辑表单的模态,它是预填充的,我添加了一些配料但保留名称不变。它节省了:
{name: "", ingredients: ing1,ing2,newIngredient}
<form role="form">
<div className="form-group">
<label htmlFor={props.recipeName}>Recipe</label>
<input
type="text"
className="form-control"
defaultValue={props.recipeName || ''}
name="recipeName"
placeholder="Recipe name"
onChange={props.handleChange.bind(this)}/>
</div>
<div className="form-group">
<label htmlFor={props.recipeIngredients}>Ingredients</label>
<textarea
type="text"
className="form-control"
defaultValue={props.recipeIngredients || ''}
placeholder="Enter ingredients separated by commas..."
onChange={props.handleChange.bind(this)}
name="recipeIngredients"></textarea>
</div>
</form>
最佳答案
将值存储在状态中。首先,将它们添加到 componentDidMount
中方法,以便在加载表单组件时拥有它们:
ComponentDidMount() {
const { recipeName } = this.props;
this.setState({ recipeName });
}
然后,onChange
每个 <input>
更新状态。因此,无论您现在以何种方式保存您的值,您都可以保存组件的状态:
updateInputValue(e) {
const { target: {value} } = e;
this.setState({ recipeName: value });
}
<input
type="text"
className="form-control"
value={this.state.recipeName}
name="recipeName"
placeholder="Recipe name"
onChange={this.updateInputValue}/>
当您到达 redux
时我建议使用 Redux Form
关于javascript - react 编辑表单创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50147030/