我有一个带有多个弹出菜单的表单。我将formik-material-ui
库用于UI,并且将重复弹出窗口重构为一个组件。当组件的代码在表单文档中就位时,一切都会按预期进行。但是,如果我将组件重构为文件并导入,则出了点问题,Formik似乎随着不断变化的弹出窗口“失去联系”:控件按预期方式绘制,并按预期方式运行,但是一旦选择完成,该值未保存到弹出窗口,并且该字段显示为空。这是导出的组件:
import React, { useContext, useEffect, useState } from 'react';
import UserContext from '../UserContext';
import { MenuItem, TextField } from '@material-ui/core';
import { Field, useField } from 'formik';
export default function UserSelect (props) {
const [ field, meta ] = useField(props);
const [ users, setUsers ] = useState([]);
const { user } = useContext(UserContext);
const { department, role , label } = props;
useEffect( () => {
async function getData(department, role) {
let res;
try{
res = await fetch(`http://localhost:4005/users/${department}/${role}`
, {
headers: new Headers({
'Authorization': 'Bearer ' + user.token
})
}
);
} catch(err) {
alert(err);
}
const { rows } = await res.json();
setUsers(rows.map((userRole, index) => (
{ index:index, value: userRole.username, label: `${userRole.surname}, ${userRole.forename}` }
)).sort((a,b)=>{return a.label > b.label}));
}
getData(department, role);
}, [user, department, role]);
return (
<React.Fragment>
<Field
{...field}
{...props}
placeholder={label}
fullWidth
select
label={label}
type="text"
value=""
variant="outlined"
margin="normal"
component={TextField}
>
{users.map(option => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</Field>
</React.Fragment>
);
};
我在这样的主文件中使用它,遍历{title, department}
元组和数组:
{departments.map( ( department, index ) => (
<Grid container spacing={1}>
<Grid item sm={6}>
<UserSelect
name={'assignedReviewer_'+index}
label={department.title+' Reviewer'}
department={department.department} role="reviewer"/>
</Grid>
</Grid>
))}
如前所述,当组件位于同一文件中时,此操作完全,但导入时失败。我应该在组件内部的meta
道具上做些什么吗?