首页 > 解决方案 > 在反应钩子形式中,如何将数据从一个属性复制到另一个状态?

问题描述

这是注册表单,我想使用 select 将值 orgTypes>name 发送到同一对象的数据的 orgType onChange

https://codesandbox.io/s/react-typescript-zm1ov?fontsize=14&fbclid=IwAR06ZifrKrDT_JFb0A-d_iu5YaSyuQ9qvLRgqS20JgAcSwLtAyaOFOoj5IQ

当我使用onChangeSelect 时,它会删除输入的所有其他数据。

import React from "react";
import { Select } from "antd";
const { Option } = Select;

const RegisterFinal = () => {
  const data = {
    orgName: "",
    orgRegNo: "",
    orgType: "",

    orgTypes: [
      { id: "1", name: "Vendor" },
      { id: "2", name: "Supplier" },
      { id: "3", name: "Vendor and Supplier" }
    ],

    errors: {}
  };

  const [values, setValues] = React.useState(data);

  const handleChange = (e: any) => {
    e.persist();
    setValues((values: any) => ({
      ...values,
      [e.target.name]: e.target.value
    }));
  };
  const handleSubmit = () => {
    console.log(values);
  };

  return (
    <React.Fragment>
      <input
        name="orgName"
        onChange={handleChange}
        placeholder="Organization Name"
        value={values.orgName}
      />
      <input
        name="orgRegNo"
        onChange={handleChange}
        placeholder="Registration Number"
        value={values.orgRegNo}
      />

      <Select //imported from antd
        id="select"
        defaultValue="Choose"
        onChange={(select: any) => {
          setValues(select);
          console.log(select); //shows Vender/Supplier, I want this value to be sent to orgType above
        }}
      >
        {data.orgTypes.map((option: any) => (
          <Option key={option.id} value={option.name}>
            {option.name}
          </Option>
        ))}
      </Select>
    </React.Fragment>
  );
};

当我使用onChangeSelect 时,它会删除输入的所有其他数据。

谢谢您的帮助

标签: reactjstypescriptantd

解决方案


setValues函数期望将值对象作为参数。相反,您将选择值传递给它。

相反,您可以这样做:

const handleSelectChange = (selectValue: any) => {
    setValues((values: any) => ({
      ...values,
      orgType: selectValue
    }));
}

handleSelectChangeonChange您的选择中使用。

在此处查看解决方案:https ://codesandbox.io/s/react-typescript-p9bjz


推荐阅读