Using a dynamic key to setState in React [duplicate]

跟風遠走 提交于 2019-12-20 03:14:29

问题


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.

here is my code.

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

and the input

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

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

Thanks in advance.


回答1:


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

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


来源:https://stackoverflow.com/questions/51282464/using-a-dynamic-key-to-setstate-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!