首页 > 解决方案 > 无法让 Popover 在对话框中的正确位置显示

问题描述

我有一个 Dialog 和一个 ListItem,当您单击它时,它会显示一个 Popover 进入编辑模式。这在使用 Modal 的旧版本的 MUI 中工作,但自从获得最新版本后不起作用,我正在尝试使用 Popover。我试图在 CodeSandox 上做一个简单的例子,但这很有效。发生的情况是 Popover 始终位于页面的左上角,而不是 ListItem。

我已将我的代码简化为对话框中的一个简单的按钮和弹出框,但仍然遇到同样的问题,并且对接下来要尝试的内容没有想法。我在控制台中得到的错误是

[Warning] Material-UI: the `anchorEl` prop provided to the component is invalid.
The anchor element should be part of the document layout.
Make sure the element is present in the document or that it's not display none.

单击该项目时,我会像示例中一样执行 event.currentTarget,这就是 console.log 的样子。

[Log] <button class="MuiButtonBase-root MuiButton-root MuiButton-text" tabindex="0" type="button"> (main.chunk.js, line 26437)
<span class="MuiButton-label">Click Me</span>
<span class="MuiTouchRipple-root">
<span class="MuiTouchRipple-ripple MuiTouchRipple-rippleVisible" style="width: 117.2006825918689px; height: 117.2006825918689px; top: -34.60034129593445px; left: -25.60034129593445px;">
<span class="MuiTouchRipple-child MuiTouchRipple-childLeaving"></span>
</span>
</span>
</button>

我什至尝试在没有修复它的对话框中执行 disablePortal。我还尝试使用 refs 修复了 anchorEl 警告,但仍相对于页面而不是元素显示。有任何想法吗?

标签: reactjsmaterial-ui

解决方案


对于在 Material UI 中遇到此问题的任何人,您都可以做几件事。

一是确保如果您有多个嵌套的功能组件,您的弹出框的 anchorEl / click 处理程序是在包含弹出框的特定功能组件中定义的。如果你有嵌套的功能组件并且父组件持有状态,它将在每次状态更改时重新渲染子组件,这可以重置 anchorEl 引用。

其次 - React.memo 可以防止对功能组件进行不必要的重新渲染(它仅在 props 不更改但仍应在子组件中获得性能优势时才有效)。


推荐阅读