反应编辑表单创建

mer*_*rko 5 javascript forms jsx reactjs

我刚开始使用 React,一直停留在编辑表单上。我需要预填充输入,但也需要能够编辑它。如果我把 defaultValue,我不能把值放在输入元素上。此时我可以输入输入,但我必须编辑两个字段(表单有两个字段)才能保存两个值。我该怎么做?

示例:我有食谱名称和成分,我用编辑表单打开模态,它是预填充的,我添加了一些成分但保持名称不变。它节省了:

{name: "", ingredients: ing1,ing2,newIngredient}
Run Code Online (Sandbox Code Playgroud)

{name: "", ingredients: ing1,ing2,newIngredient}
Run Code Online (Sandbox Code Playgroud)

Lui*_*gan 7

将值存储在状态中。首先,将它们添加到componentDidMount方法中,以便在加载表单组件时拥有它们:

ComponentDidMount() {
   const { recipeName  } = this.props;
   this.setState({ recipeName });
}
Run Code Online (Sandbox Code Playgroud)

然后,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}/>
Run Code Online (Sandbox Code Playgroud)

当你到达时,redux我建议使用Redux Form