代码之家  ›  专栏  ›  技术社区  ›  pageNotfoUnd

如何使用相同的输入框使用reactjs存储不同的值?

  •  0
  • pageNotfoUnd  · 技术社区  · 6 年前

    我想用同样的 输入框 为了输入不同的值,所以每次输入值时,我应该存储该值并显示给用户。 <input type="text" onChange={e => this.addPrice('input1', e.target.value)} /> 它被放置在模式中,因此每当模式弹出窗口打开时,使用将输入值

    1 回复  |  直到 6 年前
        1
  •  1
  •   chrisbot    6 年前

    为了使用相同的输入框向单个数组添加值,很可能必须有一个辅助操作(如按按钮),用户需要该操作指示何时存储当前值。

    state = {
      currentValue: '',
      prices: [],
    }
    
    onChange = (event) => {
      this.setState({ currentValue: event.target.value })
    }
    
    addPrice = () => {
      this.setState(prevState => ({
        prices: [...prevState.prices, this.state.currentValue]
      }))
    }
    
    ...
    
    <input type='text' onChange={this.onChange} value={this.state.currentValue} />
    <button onClick={this.addPrice}>Add Price</button>
    

    编辑:您可以在 prices 数组。如果需要键值对,则存储如下对象:

    addPrice = () => {
      this.setState(prevState => ({
        prices: [...prevState.prices, {amount: this.state.currentValue}]
      }))
    }