提问者:小点点

(REACT)如何将状态的值设置为具有属性的对象,属性也是对象?


我想接收一些输入字段的值,并将它们设置为newValue状态,但状态的某些属性本身就是对象。希望newValue状态的格式为:

{
        name : {
            firstName : 'Eithan',
            lastName :'Auralius'
        },
        rank : 7
}

现在,对象保存如下:

{
    name.firstName : 'Eithan',
    name.lastName : 'Auralius',
    rank : 7
}

有没有办法通过调整getValue函数或输入字段来实现这一点?

//State to store the created or updated user string
const [newValue, setNewValue] = useState();

//onChange triggered function to update 
const getValue = (event)=> {
    
    //Setting the value of the state using the changed input fields
    setNewValue((newValue)=> {
        return {
            ...newValue,
            [event.target.name] : event.target.value,
        }
    });
}

const submitData = (event)=> {
    event.preventDefault();
    console.log(newValue);
}

return (
    <div className='loginRegister'>
        <form onSubmit={submitData}>
            <div className='descriptionInput'><div className='description'>First Name</div>
            {//the name prop is used to set the field name in the getValue function}
            <input type="text" name='name.firstName' defaultValue={member.name.firstName} onChange={getValue}></input></div>
            <button>Submit</button>
        </form>
    </div>
);

共1个答案

匿名用户

你可以试试这个。

null

import { useState } from "react";

export default function App() {
  let defaultState = {
    name: {
      firstName: "",
      lastName: ""
    },
    rank: 0
  };
  const [newValue, setNewValue] = useState(defaultState);

  const submitData = (event) => {
    event.preventDefault();
    console.log(newValue);
  };
  //onChange triggered function to update
  const getValue = (event) => {
    //Setting the value of the state using the changed input fields
    setNewValue((newValue) => {
      return {
        name: {...newValue.name, [event.target.name]: event.target.value},
        rank: newValue.rank
      };
    });
  };

  return (
    <div>
      <form onSubmit={submitData}>
        <div>
          <div>First Name</div>
          <input
            type="text"
            name="firstName"
            defaultValue={newValue.name.firstName}
            onChange={getValue}
          ></input>
        </div>
        <button>Submit</button>
      </form>
    </div>
  );
}