ReactJS 中的 Material UI 自动完成类别

问题描述 投票:0回答:1

我正在使用 MUI 自动完成和 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
    />
  );
};
javascript reactjs ecmascript-6 material-ui formik
1个回答
0
投票

我已经使用钩子实现了一个解决方案here。 过滤后需要对

options
Autocomplete
属性值进行排序。

© www.soinside.com 2019 - 2024. All rights reserved.