如何从 e.target.name 更新状态中的对象

IT技术 javascript reactjs
2021-05-26 20:45:22

我正在尝试从这样的表单输入数据 -

<h1>Company Position</h1>
<input
    name="company.position"
    type="text"
    onChange={(e) => functions.setData(e)}
    value={data.company.position}
/>

进入这样的状态对象 -

const [ form, setValues ] = useState({
    name        : 'Jo Smith',
    email       : 'JoSmith@domain.com',
    phone       : null,
    company     : {
        name     : null,
        position : null
    }
});

使用我传入目标的 handleStateChange 函数

const handleStateChange = (e) => {
    e.preventDefault();
    setValues({
        ...form,
        [e.target.name]: e.target.value
    });
};

我似乎无法更新状态内部的公司对象,我认为它会将 company.name 识别为目标名称。

任何帮助,将不胜感激。

2个回答

e.target.namecompany.position,您不能设置嵌套属性,例如obj["company.position"],您必须将其拆分:

<input
  name="company.position"
  type="text"
  onChange={e => functions.setData(e)}
  value={data.company.position}
/>;

const handleStateChange = e => {
  e.preventDefault();
  const [section, key] = e.target.name.split(".");

  // section is : company
  // key is : position

  if (key) {
    // if you have nested keys to update
    setValues({
      ...form,
      [section]: {
        ...form[section],
        [key]: e.target.value
      }
    });
  } else {
    // if you're updating on the first level
    setValues({
      ...form,
      [section]: e.target.value
    });
  }
};
const nested = e.target.name.split(".");
    const [section, key] = nested; 
     if(nested.length > 2){
        let total = nested.length;
        let ultimo = nested[total-1];
        saveclinicHistory({
            ...clinicHistory,
            [section]: {//patient
                ...clinicHistory[section],
                [key]: {//address
                    ...clinicHistory[section][key],
                    [ultimo]:e.target.value

                }
            }
        });