【发布时间】:2021-06-05 03:51:37
【问题描述】:
我正在使用React Portal 创建工具提示。我想让按钮的底部与工具提示的顶部相邻,并且它们在右侧相互对齐。
如果我不使用门户,我可以使用绝对/相对来定位按钮对应的工具提示。
但是portal会让这两个元素互不认识,所以我需要调用getBoundingClientRect来获取按钮的位置并计算出tooltip的位置。
那么如何设置工具提示的样式对象来实现呢?
顺便说一句,内容的大小是动态的,宽度从 100px 到 200px 不等,高度从 50px 到 150px 不等。我希望不要为它们使用硬编码值。
更新
请不要问我为什么不选择这个库或那个库。 只要我不使用反应门户,我就已经说明了这些库的解决方案。
请花时间阅读官方的 react 门户文档,该文档充分解释了当您的工具提示放置在 DOM 层次结构中并且由于父容器的z-index 而被其他元素覆盖或重叠的情况。因此,我选择使用 react portal 将其放置在顶层的根节点下。
const button = document.getElementById('button');
const buttonRect = button.getBoundingClientRect();
const tooltip = document.getElementById('tooltip');
// tooltip.style.? = ?
// |------|
// |button|
// |------|
// |-------------|
// | |
// | tooltip |
// | |
// |-------------|
#app-root {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: #999;
display: flex;
justify-content: center;
align-items: center;
}
#portal-root {
position: fixed;
top: 0;
left: 0;
width: 0;
height: 0;
}
.content {
width: 200px;
height: 100px;
background-color: #000;
}
<div id="app-root">
<button id="button">button</button>
</div>
<div id="portal-root">
<div id="tooltip">
<div class="content"><div>
</div>
</div>
【问题讨论】:
-
按钮元素下没有放portal-root div是什么原因?
-
为什么不使用tippy之类的工具提示? github.com/atomiks/tippyjs-react