【问题标题】:React edit form creating反应编辑表单创建
【发布时间】:2018-10-13 07:04:21
【问题描述】:

我刚开始使用 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>

【问题讨论】:

标签: javascript forms reactjs jsx


【解决方案1】:

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

ComponentDidMount() {
   const { recipeName  } = this.props;
   this.setState({ recipeName });
}

然后,每个&lt;input&gt;onChange 更新状态。因此,无论您现在以哪种方式保存值,都可以保存组件的状态:

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

【讨论】:

    【解决方案2】:

    您需要将传入的道具的值放入您的初始状态。您需要在构造函数中执行此操作。

    目前您的状态仅通过更改事件进行更新,但从未设置初始状态(可能无论如何。我只是猜测这是因为您没有包含完整的代码)。

    【讨论】:

      猜你喜欢
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-31
      • 2013-08-20
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多