在react hooks形式中,如何将数据从一个属性复制到另一状态?

时间:2019-06-22 13:19:17

标签: reactjs typescript antd

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

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

当我使用Select的onChange时,它将删除输入的所有其他数据。

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>
  );
};

当我使用Select的onChange时,它将删除输入的所有其他数据。

谢谢您的帮助

1 个答案:

答案 0 :(得分:1)

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

相反,您可以这样做:

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

,然后在您选择的handleSelectChange中使用onChange

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