我正在使用 MUI Autocomplete 和 Formik,我想将其分组。如果它没有sub_accounts
,那么它不应该有标题标签。像这样的东西:https://mui.com/material-ui/react-autocomplete/#grouped
代码沙箱 ------> 点击此处
UI 上的预期结果类似于:
小钱
银行现金 - 美国银行
- 美国银行 - 单一业主
- 美国银行 - 法人实体
现金
CIB-越南银行
- 越南银行个人
- 越南银行支票账户
Petty Cash
、Cash In Bank - Bank of America
、Cash
和CIB - Bank of Vietnam
应对齐。
Cash In Bank - Bank of America
和 CIB - Bank of Vietnam
无法单击/选择 - 只能sub_accounts
选择它以及Petty Cash
和Cash
。
代码
export const CashAccountAutocomplete = ({
field,
form: { touched, errors, setFieldValue, values },
disabled,
...props
}) => {
const [inputValue, setInputValue] = useState("");
const handleChange = (_, newValue, reason) => {
if (reason === "clear") {
setFieldValue(field.name, { id: "", name: "" });
return;
}
setFieldValue(field.name, newValue);
};
const handleInputChange = (_, newInputValue) => {
setInputValue(newInputValue);
};
const extractSubAccounts = (accounts) => {
if (!Array.isArray(accounts)) {
console.error("Invalid accounts data. Expected an array.");
return [];
}
return accounts.flatMap(
({ id, name, sub_accounts }) =>
sub_accounts && sub_accounts.length > 0
? extractSubAccounts(sub_accounts) // Recursively extract sub-accounts
: [{ id, name }] // Include the account if it has no sub-accounts
);
};
const filteredData = extractSubAccounts(accounts);
return (
<Autocomplete
{...field}
disabled={disabled}
getOptionLabel={(option) =>
typeof option === "string" ? option : option?.name || ""
}
renderOption={(props, option) => {
return (
<li {...props} key={option.id}>
{option?.name}
</li>
);
}}
filterOptions={(x) => x}
options={filteredData || []}
autoComplete
includeInputInList
filterSelectedOptions
noOptionsText={"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].id)
}
/>
)}
fullWidth
/>
);
};
更新
extractSubAccounts
辅助函数以仅设置isHeader
元素上的属性将是标题,然后isSelectable
如果没有子数组选项也设置一个属性。更新回调
renderOptions
以检查每个列表项inHeader
和isSelectable
属性,其想法是作为标题和选项的列表项应该是可选择的并接收"MuiAutocomplete-option"
CSS 类,然后有条件地撤消选项具有的填充,以便标题保持对齐。我在这里使用钩子实现了一个解决方案。您需要对过滤后
options
的属性值进行排序。Autocomplete