reactjs - React Material-UI 菜单 anchor 被 react 窗口列表破坏

标签 reactjs material-ui

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

Here's an example sandbox 。沙箱非常具体于我如何使用相关组件。

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

最佳答案

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

Edit BigList menu

这是您在 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>
  );
};

我将其更改为以下内容:

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>
  );
};

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

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

关于reactjs - React Material-UI 菜单 anchor 被 react 窗口列表破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192935/

相关文章:

javascript - 为什么依赖 useEffect 是数组状态而不是无限循环

reactjs - 如何使用 Jest 正确模拟 React Navigation 的 getParam 方法

javascript - 如何处理在服务器上更新的 webpack chunk?

material-ui - 无论如何要将 Material UI 选项卡设置为默认选择?

javascript - material-ui的TextField、DropDownMenu组件如何获取数据?

reactjs - 将 props 传递给 TS 中的 makeStyle

reactjs - react 播放器和授权需要问题

reactjs - 如何延迟安装 Material UI 标签面板或知道标签面板何时可见?

javascript - Material UI/material-ui appbar leftnav 切换不起作用

reactjs - @reach/router - 路径更新但单击链接时组件不呈现