reactjs 如何在选中的文本上显示工具提示组件?

p4rjhz4m  于 2023-01-02  发布在  React
关注(0)|答案(3)|浏览(246)

如中:

来自材料界面React框架的工具提示。
一些想法:

  • <span> Package 选定的文本,并使用该元素作为工具提示的引用节点(我猜太复杂了)
  • 创建工具提示w/o子项并指定基于选定文本的绝对位置

还有别的主意吗?

z8dt9xmd

z8dt9xmd2#

Medium.com 使用popper.js。我通过搜索Medium的HTML中的标记参数发现了这一点。

<div class="bz fx mc yw"
     style=
"position: absolute; inset: auto auto 0px 0px; transform: translate(692px, 1233px);"
     data-popper-reference-hidden="false"
     data-popper-escaped="false"
     data-popper-placement="top">

https://popper.js.org/
它做的事情,它reposites弹出,如果你滚动,我检查。

waxmsbnn

waxmsbnn3#

我使用了弹出器组件,而不是工具提示组件链接:https://mui.com/material-ui/react-popper/#virtual-element
演示:https://codesandbox.io/s/iztu66?file=/demo.js
代码

import * as React from 'react';
import Popper from '@mui/material/Popper';
import Typography from '@mui/material/Typography';
import Fade from '@mui/material/Fade';
import Paper from '@mui/material/Paper';

export default function VirtualElementPopper() {
  const [open, setOpen] = React.useState(false);
  const [anchorEl, setAnchorEl] = React.useState(null);

  const handleClose = () => {
    setOpen(false);
  };

  const handleMouseUp = () => {
    const selection = window.getSelection();

    // Resets when the selection has a length of 0
    if (!selection || selection.anchorOffset === selection.focusOffset) {
      handleClose();
      return;
    }

    const getBoundingClientRect = () =>
      selection.getRangeAt(0).getBoundingClientRect();

    setOpen(true);
    setAnchorEl({
      getBoundingClientRect,
    });
  };

  const id = open ? 'virtual-element-popper' : undefined;

  return (
    <div onMouseLeave={handleClose}>
      <Typography aria-describedby={id} onMouseUp={handleMouseUp}>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ipsum purus,
        bibendum sit amet vulputate eget, porta semper ligula. Donec bibendum
        vulputate erat, ac fringilla mi finibus nec. Donec ac dolor sed dolor
        porttitor blandit vel vel purus. Fusce vel malesuada ligula. Nam quis
        vehicula ante, eu finibus est. Proin ullamcorper fermentum orci, quis finibus
        massa. Nunc lobortis, massa ut rutrum ultrices, metus metus finibus ex, sit
        amet facilisis neque enim sed neque. Quisque accumsan metus vel maximus
        consequat. Suspendisse lacinia tellus a libero volutpat maximus.
      </Typography>
      <Popper
        id={id}
        open={open}
        anchorEl={anchorEl}
        transition
        placement="bottom-start"
      >
        {({ TransitionProps }) => (
          <Fade {...TransitionProps} timeout={350}>
            <Paper>
              <Typography sx={{ p: 2 }}>The content of the Popper.</Typography>
            </Paper>
          </Fade>
        )}
      </Popper>
    </div>
  );
}

您可以在淡入淡出组件之后或在纸张组件内部添加自己的按钮。

相关问题