React Material-UI 菜单锚被反应窗口列表破坏

cov*_*ise 7 reactjs material-ui

我在项目中使用 Material-UI 和 React-window。我的问题是,当该元素位于反应窗口虚拟化列表中时,material-ui 菜单组件不会锚定到所提供的元素。该菜单将出现在屏幕的左上角,而不是固定在打开它的按钮上。当在非虚拟化列表中使用它时,它会按预期工作。菜单正确地锚定到打开它的按钮。

这是一个沙箱示例。沙箱非常具体于我如何使用相关组件。

有关如何解决此问题的任何指导吗?

Rya*_*ell 4

这是沙箱的修改版本,可以修复此问题:

编辑 BigList 菜单

这是您的初始代码BigList

const BigList = props => {
  const { height, ...others } = props;
  const importantData = Array(101 - 1)
    .fill()
    .map((_, idx) => 0 + idx);
  const rows = ({ index, style }) => (
    <FancyListItem
      index={index}
      styles={style}
      text="window'd (virtual): "
      {...others}
    />
  );

  return (
    <FixedSizeList
      height={height}
      itemCount={importantData.length}
      itemSize={46}
      outerElementType={List}
    >
      {rows}
    </FixedSizeList>
  );
};
Run Code Online (Sandbox Code Playgroud)

我将其更改为以下内容:

const Row = ({ data, index, style }) => {
  return (
    <FancyListItem
      index={index}
      styles={style}
      text="window'd (virtual): "
      {...data}
    />
  );
};

const BigList = props => {
  const { height, ...others } = props;
  const importantData = Array(101 - 1)
    .fill()
    .map((_, idx) => 0 + idx);
  return (
    <FixedSizeList
      height={height}
      itemCount={importantData.length}
      itemSize={46}
      outerElementType={List}
      itemData={others}
    >
      {Row}
    </FixedSizeList>
  );
};
Run Code Online (Sandbox Code Playgroud)

重要的区别在于,它Row现在是一致的组件类型,而不是在每次渲染时都重新定义BigList。使用您的初始代码,每次渲染都会BigList导致重新安装所有元素,FancyListItem而不仅仅是重新渲染,因为它周围表示“行”类型的函数是每次渲染时的新函数BigList。这样做的一个影响是,当您尝试确定其位置时,您传递到的锚元素Menu不再安装Menu,并且anchorEl.getBoundingClientRect() 提供了 0,0 的 x,y 位置。

您会注意到在react-window文档(https://react-window.now.sh/#/examples/list/fixed-size)中Row,组件是在组件外部定义的Example,类似于代码的固定版本现在已结构化。