当基础组件重新渲染时,为什么popper跳到左上角?

问题描述

我正在使用Material-UI Popper组件(依次使用popper.js)来创建一个悬停工具栏。在大多数情况下,它运行良好,除了一种奇怪的行为:

  1. 选择一些文本:悬停工具栏出现在文本上方-如预期。
  2. 选择工具栏中的任何按钮:执行适当的操作。但是,工具栏会跳到窗口的左上角。参见下文。

enter image description here

您可以在my Storybook中尝试这种行为-只需选择一些文本,然后单击“ T”按钮之一即可。

基本问题围绕着弹出器的位置:

  1. 用户选择一些文本时,将创建一个假的虚拟元素并将其作为锚元素传递给Popper。 Popper使用此anchorEl定位悬停工具栏。到目前为止一切顺利。
  2. 用户单击工具栏上的按钮时,悬停的工具栏将跳到窗口的左上方。

我猜想这是因为基础组件重新渲染时锚元素丢失了。我不知道为什么,但这只是我的理论。有人可以帮我解决这个问题吗?

计算anchorEl代码位于React useEffect()内部。我已经确保useEffect的依赖项列表是正确的。我看到工具栏跳转时,useEffect()没有被调用,这意味着anchorEl没有被重新计算。这使我相信工具栏应保持其当前位置不变,而不是跳到(0,0)。但这没有发生:-(。

这是工具栏组件中的useEffect()代码。您可以在my repo中找到完整的代码。任何帮助将不胜感激。

useEffect(() => {
    if (editMode === 'toolbar') {
        if (isTextSelected) {
            const domSelection = window.getSelection();
            if (domSelection === null || domSelection.rangeCount === 0) {
                return;
            }
            const domrange = domSelection.getRangeAt(0);
            const rect = domrange.getBoundingClientRect();
            setAnchorEl({
                clientWidth: rect.width,clientHeight: rect.height,getBoundingClientRect: () =>
                    domrange.getBoundingClientRect(),});
            setToolbarOpen(true);
        } else {
            setToolbarOpen(false);
        }
    } else {
        setToolbarOpen(false);
    }
},[editMode,isTextSelected,selection,selectionStr]);

解决方法

我相信您的domRangetoggleBlock工作之后不再有效(由于dom节点已被替换),因此getBoundingClientRect不再返回任何有意义的内容。

您应该能够通过重做使范围位于anchorEl的getBoundingClientRect中的工作来解决此问题。也许像下面这样(我没有尝试执行它,所以不能保证没有小错误):

const getSelectionRange = () => {
  const domSelection = window.getSelection();
  if (domSelection === null || domSelection.rangeCount === 0) {
    return null;
  }
  return domSelection.getRangeAt(0);
};
useEffect(() => {
  if (editMode === "toolbar") {
    if (isTextSelected) {
      const domRange = getSelectionRange();
      if (domRange === null) {
        return;
      }
      const rect = domRange.getBoundingClientRect();
      setAnchorEl({
        clientWidth: rect.width,clientHeight: rect.height,getBoundingClientRect: () => {
          const innerDomRange = getSelectionRange();
          return innerDomRange === null
            ? null
            : innerDomRange.getBoundingClientRect();
        }
      });
      setToolbarOpen(true);
    } else {
      setToolbarOpen(false);
    }
  } else {
    setToolbarOpen(false);
  }
},[editMode,isTextSelected,selection,selectionStr]);