我在使用
Formik
和 MUI
自动完成多个项目时遇到问题。
例如:如果您通过输入“铅笔”进行搜索,问题是,它不会突出显示它。如果您单击它,您仍然可以选择它两次。
预期结果: 我们将能够选择一个或多个项目。当选择一个项目时,其复选框将被选中,并且它会突出显示。
这是我的代码和框:CODESANDBOX
const TestAutocomplete = ({
field,
form: { touched, errors, setFieldValue, values },
...props
}) => {
const [inputValue, setInputValue] = useState("");
const debouncedInputValue = useDebounceValue(inputValue, 500);
const { data: response, isLoading } = useFetchSubledgersQuery({
pageNumber: 0,
pageSize: 50,
search: debouncedInputValue,
});
const handleChange = (_, newSelectedValues, reason) => {
if (reason === "clear") {
setFieldValue(field.name, []);
return;
}
setFieldValue(field.name, newSelectedValues);
};
const handleInputChange = (_, newInputValue) => {
setInputValue(newInputValue);
};
return (
<Autocomplete
{...field}
multiple
getOptionLabel={(option) =>
typeof option === "string" ? option : option?.name || ""
}
filterOptions={(x) => x}
options={response || []}
autoComplete
includeInputInList
fullWidth
noOptionsText={isLoading ? "Loading..." : "No data"}
onChange={handleChange}
inputValue={inputValue}
onInputChange={handleInputChange}
renderInput={(params) => (
<TextField
{...params}
{...props}
error={touched[field.name] && errors[field.name] ? true : false}
helperText={
touched[field.name] &&
errors[field.name] &&
String(errors[field.name])
}
/>
)}
renderOption={(props, option, { selected }) => (
<li {...props}>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={values?.[field.name]?.some(
(selectedValue) => selectedValue.id === option.id
)}
/>
{option?.name}
</li>
)}
renderTags={(value, getTagProps) =>
value.map((option, index) => (
<Chip
key={option.id}
label={option.name}
{...getTagProps({ index })}
/>
))
}
/>
);
};
在更新表单状态之前删除自动完成的“新值”的重复项。
示例:
const handleChange = (_, newSelectedValues, reason) => {
if (reason === "clear") {
setFieldValue(field.name, []);
return;
}
const idSet = new Set();
const deduplicated = newSelectedValues.reduce((values, current) => {
if (!idSet.has(current.id)) {
idSet.add(current.id);
values.push(current);
}
return values;
}, []);
setFieldValue(field.name, deduplicated);
};