【问题标题】:ReactJS - dynamically updating form with double inputReactJS - 使用双输入动态更新表单
【发布时间】:2019-03-30 10:50:39
【问题描述】:

我正在尝试使用双重输入更新表单,每次用户单击“添加”按钮并使用他们的值改变状态时,我希望这 2 个输入被“连接”。如果我用图形显示我正在尝试做的事情会更容易理解:

[input] [second input] [remove button]
[input] [second input] [remove button]
[input] [second input] [remove button] ...

当我尝试只动态生成一个输入时,这要容易得多,目前我什至没有完整的代码,因为我不知道该怎么做,但我有一些部分,这里是:

状态:

  stuff: {
            item: [],
            quantity: []
        },

这是只动态添加一个输入字段的代码:

// i mapped stuff because before i only had one array and like this-> stuff: []   
return this.state.stuff.map((element, index) => 
     <div key={index}>
        <input type="text" value={element||''} onChange={this.handleChange.bind(this, index)} />
        <input type='button' value='remove' onClick={this.removeInput.bind(this, index)}/>
     </div>          
 )

  handleChange(index, event) {
 let stuff = [...this.state.stuff];
 stuff[index] = event.target.value;
 this.setState({ stuff });
 }

     add(){
        this.setState(previousState => ({ stuff: [...previousState.stuff,'']}))
 }

     removeInput(index){
   let stuff = [...this.state.stuff];
   stuff.splice(index,1);
   this.setState({ stuff });
 }

说实话,我只是在尝试每一个想法,在 add() 函数中,我无法完全了解如何将 '' 添加到填充数组使代码工作,如果有人解释这一点并为我提供我想做的解决方案我会很感激的。

【问题讨论】:

    标签: javascript arrays reactjs state


    【解决方案1】:

    我无法完全理解在 stuff 数组中添加 '' 是如何使代码工作的

    如果您查看render() 方法,您会看到this.state.stuff.map(...),因此您基本上将stuff 数组中的每个值都映射到相关输入。因此,如果您将另一个值添加到 stuff,组件会重新呈现并映射新的输入。


    现在要为每一行添加两个输入,您可以保留两个数组,但这会使以后管理数据变得更加困难。相反,我会使用一个对象数组,其中包含一个项目和数量属性。为此,在 add() 方法中添加新对象:

      this.setState(({ stuff }) => ({ stuff: [...stuff, { item: "", quantity: 0 }));
    

    然后您必须更改 render() 内的映射以显示这些对象:

     this.state.stuff.map(({ item, quantity }, index) => (
      <div>
       Item: <input value={item} onChange={e => this.update(index, "item", e.target.value)} />
       Quantity: <input value={quantity} onChange={e => this.update(index, "quantity", e.target.value)} />
      </div>
     ));
    

    现在唯一剩下的就是一个更新方法,它不仅需要一个索引,还需要改变的关键:

     update(index, key, value) {
       this.setState(({ stuff }) => ({ stuff: stuff.map((it, i) => i === index ? { ...it, [key]: value }, it)) }));
     }
    

    【讨论】:

      猜你喜欢
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 2020-04-13
      相关资源
      最近更新 更多