【问题标题】:How to position tooltip in react portal?如何在反应门户中定位工具提示?
【发布时间】: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>

【问题讨论】:

标签: css reactjs


【解决方案1】:

这是你想要达到的目标吗?

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;
  flex-flow: column;
  justify-content: center;
  align-items: center;
}

#portal-root {
  position: relative;
}

.content {
  width: 200px;
  height: 100px;
  background-color: #000;
}
<div id="app-root">
  <button id="button">button</button>
  <div id="portal-root">
  <div id="tooltip">
    <div class="content"><div>
  </div>
</div>
</div>

【讨论】:

  • A typical use case for portals is when a parent component has an overflow: hidden or z-index style, but you need the child to visually “break out” of its container. For example, dialogs, hovercards, and tooltips. 这就是门户根目录位于顶层的原因。
  • 在你的一段代码中,不需要使用react portal,只需将div放在dom树中也可以。但在实际情况下,按钮可能位于可滚动列表或表格行内,如果不放在顶层根节点内,则工具提示将被其他元素覆盖。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-14
  • 1970-01-01
相关资源
最近更新 更多