在React中使用动态键setState [英] Using a dynamic key to setState in React

查看:136
本文介绍了在React中使用动态键setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

From an input field I am sending the value as an argument to the function that sets state. I have multiple input fields so would like to use their name (which is equal to their state key) to then use the same function and pass in the key and value to the function that sets state.

这是我的代码。

<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参数有效,但键参数不起作用。

the text argument works, but the key argument does not.

提前致谢。

推荐答案

使用动态密钥设置状态时,需要将密钥包装在内 [] 喜欢

When setting state with a dynamic key, you need to wrap the key within [] like

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

这篇关于在React中使用动态键setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆