1

当有超过 200 个选项时,Material-UI Select 会滞后。

这是一个已知问题 - https://github.com/mui-org/material-ui/issues/17001

我尝试使用useVirtual钩子来解决它react-virtual

到目前为止,它效果不佳。

我创建了这个沙箱:https ://codesandbox.io/s/lucid-ritchie-j2c13?file=/src/Demo.tsx

如果还有其他方法可以虚拟化 中的项目Material-UI Select,我会接受。

这是我的代码:

import * as React from "react";
import Select from "@material-ui/core/Select";
import MUIMenuItem from "@material-ui/core/MenuItem";
import { useVirtual } from "react-virtual";

export default function Demo() {
  const parentRef = React.useRef<any>();
  const [value, setValue] = React.useState(1);

  const rowVirtualizer = useVirtual({
    size: 10000,
    parentRef,
    estimateSize: React.useCallback(() => 35, []),
    overscan: 5
  });
  return (
    <Select
      MenuProps={{
        ref: parentRef,
        style: {
          height: "200px",
          width: `400px`,
          overflow: "auto"
        },
        anchorOrigin: {
          vertical: "bottom",
          horizontal: "left"
        },
        getContentAnchorEl: null,
        MenuListProps: {
          style: {
            height: `${rowVirtualizer.totalSize}px`,
            width: "100%",
            position: "relative"
          }
        }
      }}
      value={value}
      onChange={(e: any) => setValue(e.target.value)}
    >
      {rowVirtualizer.virtualItems.map(({ index, size, start }) => (
        <MUIMenuItem
          style={{
            position: "absolute",
            top: 0,
            left: 0,
            width: "100%",
            height: `${size}px`,
            transform: `translateY(${start}px)`
          }}
          key={index}
          value={String(index)}
        >
          <div>{index}</div>
        </MUIMenuItem>
      ))}
    </Select>
  );
}

4

0 回答 0