reactjs - 在反应钩子形式中,如何将数据从一个属性复制到另一个状态?
问题描述
这是注册表单,我想使用 select 将值 orgTypes>name 发送到同一对象的数据的 orgType onChange
。
当我使用onChange
Select 时,它会删除输入的所有其他数据。
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>
);
};
当我使用onChange
Select 时,它会删除输入的所有其他数据。
谢谢您的帮助
解决方案
setValues
函数期望将值对象作为参数。相反,您将选择值传递给它。
相反,您可以这样做:
const handleSelectChange = (selectValue: any) => {
setValues((values: any) => ({
...values,
orgType: selectValue
}));
}
并handleSelectChange
在onChange
您的选择中使用。
推荐阅读
- python - 你可以在 python 的子包中隐藏导入的模块吗?
- junit - 在 try with resource block 中模拟变量以使用 mockito 抛出 IOException
- c# - 将 [CallerMemberName] 属性与 Func 委托一起使用
- html - 如何为以下场景添加断点?
- django - 通过 git 同步 postgres 数据库
- xml - 无法在 Shell 中解析 XML
- javascript - 即使正文包含不在模式中的参数,findByIdAndUpdate 也不会失败
- node.js - 在nestJs中注入mongodb连接不起作用
- arm - 代码大小比较 Cortex M3:IAR ARM 与 Keil µVision
- cloud-foundry - Cloud Foundry 本地 - 未找到液滴