我正在使用MUI AutoComplete和Formik,我想将其分组到类别中.如果它没有sub_accounts,那么它不应该有标题标签.类似于这样:https://mui.com/material-ui/react-autocomplete/#grouped

CODESANDBOX ------> CLICK HERE

UI上的预期结果类似于:

  • 零用金

  • 现金存入银行-美国银行

    • 美国银行-单一业主
    • 美国银行-企业实体
  • 现金

  • CIB -越南银行

    • 越南银行个人
    • 越南银行支票存款

零用金, 现金存入银行-美国银行, 现金 and CIB -越南银行 should be aligned.

现金存入银行-美国银行 and CIB -越南银行 cannot be clicked/selected - only its sub_accounts can be selected as well as 零用金 and 现金.

CODE

export const 现金AccountAutocomplete = ({
  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 helper函数,仅在将是头的元素上设置isHeader属性,然后如果没有子数组选项,还设置isSelectable属性.

const extractSubAccounts = (accounts) => {
  if (!Array.isArray(accounts)) {
    console.error("Invalid accounts data. Expected an array.");
    return [];
  }

  return accounts.flatMap(({ name, sub_accounts, ...account }) => [
    {
      ...account,
      name,
      isHeader: true,
      isSelectable: !sub_accounts?.length,
    },
    ...sub_accounts,
  ]);
};

更新renderOptions回调以判断both每个列表项的inHeaderisSelectable属性,其 idea 是,作为标题104也选项的列表项应该是可 Select 的,并接收"MuiAutocomplete-option"个CSS类,然后还有条件地撤销选项具有的填充,以便标题保持对齐.

renderOption={(props, option) => {
  return (
    <li
      key={option.id}
      {...(!option.isHeader || option.isSelectable ? props : {})}
      style={{
        paddingLeft:
          option.isHeader || option.isSelectable ? "1rem" : "2rem",
      }}
    >
      {option.isHeader && !option.isSelectable
        ? <strong>{option.name}</strong>
        : option.name}
    </li>
  );
}}

enter image description here

Javascript相关问答推荐

Fastify错误:CORS策略已阻止从起源api-dev.example.com上的MLhttp请求

如何使用JavaScript动态地将CSS应用于ToDo列表?

Vue:ref不会创建react 性属性

如何在使用fast-xml-parser构建ML时包括属性值?

TypeScript索引签名模板限制

成功完成Reducers后不更新状态

Google maps API通过API返回ZERO_RESULTS,以获得方向请求,但适用于Google maps

当试图显示小部件时,使用者会出现JavaScript错误.

将旋转的矩形zoom 到覆盖它所需的最小尺寸&S容器

简单的PayPal按钮集成导致404错误

制作钢琴模拟器,并且在控制台中不会执行或显示该脚本

当输入字段无效时,我的应用程序不会返回错误

JS Animate()方法未按预期工作

MongoDB通过数字或字符串过滤列表

为什么在运行于<;img>;事件处理程序中的JavaScript中x和y是不可变的?

在ChartJS中使用spanGaps时,是否获取空值的坐标?

固定动态、self 调整的优先级队列

我们是否可以在reactjs中创建多个同名的路由

Firefox的绝对定位没有达到预期效果

ReactJS在类组件中更新上下文