简体   繁体   中英

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?

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.

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

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

[name]: value

In your case, { formInput: { username:"", password: "" }

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

I think you can initialize your formObject as empty json and

this.state = {formInput: {}}

Later onChange you can set the value something like

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

and conditionaly check if (this.state.formInput.username) ? this.state.formInput.username : '' (this.state.formInput.username) ? this.state.formInput.username : '' to value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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