【问题标题】:Using a dynamic key to setState in React [duplicate]在 React 中使用动态键设置状态 [重复]
【发布时间】:2018-12-19 07:36:14
【问题描述】:

从输入字段中,我将值作为参数发送给设置状态的函数。我有多个输入字段,因此想使用它们的名称(等于它们的状态键)然后使用相同的函数并将键和值传递给设置状态的函数。

这是我的代码。

<Modal
  onTextChange={(text, key) => {
    this.setState({
      event: {
        key: text
      }
    })
  }}
/>

和输入

<input
  type="date"
  name="dateStart"
  onKeyUp={event => this.props.onTextChange(event.target.value, event.target.name)
/>

text 参数有效,但 key 参数无效。

提前致谢。

【问题讨论】:

    标签: javascript reactjs setstate


    【解决方案1】:

    使用动态密钥设置状态时,需要将密钥包裹在[]

    <Modal
      onTextChange={(text, key) => {
        this.setState({
          event: {
            [key]: text
          }
        })
      }}
    />
    

    【讨论】:

    • 完美,我意识到我也需要使用新副本设置状态。谢谢老兄。
    猜你喜欢
    • 2020-02-09
    • 2019-08-23
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 2018-12-25
    • 2016-11-07
    • 2017-05-30
    • 1970-01-01
    相关资源
    最近更新 更多