简体   繁体   English

使用动态键名设置对象状态的最佳方法? - 反应

[英]Best way to set state of object using dynamic key name? - reactjs

I have a react state like:我有一个反应状态,如:

this.state = {
  formInputs: {
    username: '',
    password: '',
    passwordConfirm: '',
  },
  handleChange = () => {
    const {target: {name, value}} = event;
    this.setState({
      [name as keyof formInputs]: value
    });
  }
};

How can I change this line ( [name as keyof formData]: value) to a JavaScript instead of Typescript?如何将此行([name as keyof formData]: value)更改为 JavaScript 而不是 Typescript?

We can use Computed property names concept to compute the object property name dynamically.我们可以使用计算属性名称概念来动态计算对象属性名称。 For that we need to put the expression inside [] .为此,我们需要将表达式放在[]

When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.当需要处理多个受控输入元素时,可以给每个元素添加一个name属性,让处理函数根据event.target.name的值来选择要做什么。

For your state为您的州

this.setState({
    formInput: {
        ...this.state.formInput,
        [event.target.name]: event.target.value
    }
})

Sandbox for your reference: https://codesandbox.io/s/react-basic-example-p7ft8沙盒供您参考: https : //codesandbox.io/s/react-basic-example-p7ft8

import React, { Component } from "react";

export default class Login extends Component {
  state = {
    formInputs: {
      email: "",
      password: ""
    }
  };

  handleOnChange = event => {
    this.setState({
      formInput: {
        ...this.state.formInput,
        [event.target.name]: event.target.value
      }
    });
  };

  render() {
    return (
      <form>
        <label>Email</label>
        <input type="text" name="email" onChange={this.handleOnChange} />
        <label>Password</label>
        <input type="password" name="password" onChange={this.handleOnChange} />
      </form>
    );
  }
}


You can directly use Bracket_notation您可以直接使用Bracket_notation

[name]: value

In your case, { formInput: { username:"", password: "" }在你的情况下,{ formInput: { username:"", password: "" }

this.setState({
    formInput: {
        ...this.state.formInput,
        [name]: value
    }
});

I think you can initialize your formObject as empty json and我认为你可以将你的formObject初始化为空的 json 和

this.state = {formInput: {}}

Later onChange you can set the value something like稍后 onChange 你可以设置类似的值

this.setState({formInput[event.target.name]: event.target.value})

and conditionaly check if (this.state.formInput.username) ? this.state.formInput.username : ''并有条件地检查 if (this.state.formInput.username) ? this.state.formInput.username : '' (this.state.formInput.username) ? this.state.formInput.username : '' to value (this.state.formInput.username) ? this.state.formInput.username : '' to value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM