我从API调用中获取一个JSON对象数组,分别是:
[
{
"staffTypeID":103,
"staffType":"3",
"staffPermissionType":"Regular",
"staffRoleID":31,
"staffRole":"Sales_Regular"
},
{
"staffTypeID":52,
"staffType":"1",
"staffPermissionType":"Admin",
"staffRoleID":11,
"staffRole":"Admin"
}
]
我正在使用 Formik Material UI 将其列在 Select 上,代码如下:
<Field name="StaffType" label="Staff Type" component={Select}
options={Object.keys(StaffTypes).map((StaffType) =>
({value: StaffTypes[StaffTypes].staffTypeID, label: StaffTypes[StaffTypes].staffRole}))}/>
我也有一个常量来分配值:
const [staff,setStaff]=useState('');
我需要通过在下拉列表中选择来将 json 对象的值设置为员工常量。通过单击"选择"下拉列表,应将员工常量分配给
{
"staffTypeID":103,
"staffType":"3",
"staffPermissionType":"Regular",
"staffRoleID":31,
"staffRole":"Sales_Regular"
}
所以我可以使用其他代码作为<h2>{staff.staffPermissionType.toUpperCase()}</h2>
任何人都可以在这方面帮助我。
我不熟悉 Formik,但能够完成我认为您正在此代码沙箱上尝试做的事情。
Formik 组件为子组件提供当前表单值,因此您根本不需要 useState。
这是相关部分:
import React from "react";
import { Formik, Form, Field } from "formik";
import { Select } from "material-ui-formik-components/Select";
const StaffTypes = [
{
staffTypeID: 103,
staffType: "3",
staffPermissionType: "Regular",
staffRoleID: 31,
staffRole: "Sales_Regular"
},
{
staffTypeID: 52,
staffType: "1",
staffPermissionType: "Admin",
staffRoleID: 11,
staffRole: "Admin"
}
];
const FormCmp = ({ values, handleChange }) => {
// get the currently selected StaffType id
const staffRoleID = (values || {}).StaffType;
// look up the item in the options array
const staffType = StaffTypes.find(x => x.staffRoleID === staffRoleID);
return (
<div>
{/* display the selected staffRole */}
<h1>{staffType && staffType.staffRole}</h1>
<Form>
<Field
name="StaffType"
label="Staff Type"
options={StaffTypes.map(entry => ({
value: entry.staffRoleID,
label: entry.staffRole
}))}
component={Select}
/>
</Form>
</div>
);
};
function StaffTypeForm() {
return (
<div>
<Formik initialValues={{ StaffType: StaffTypes[0].staffRoleID }}>
{FormCmp}
</Formik>
</div>
);
}
export default StaffTypeForm;