在特定参考上渲染工具顶部元素

问题描述 投票:0回答:1

仅当用户单击此按钮且特定条件成立时,我才想在按钮上呈现TooltipComponent

我对react-tooltip库很熟悉,但是我不想使用它,我对此库并不满意。该库中有一个ReactTooltop.show函数。

我希望能够做类似的事情(同样,不使用此lib:

const onBtnClick = () => {
    if(...condition...){
       MyTooltip.show(btnRef, ...); // maybe pass some arguments like tooltip text...
    }
}

任何想法我该如何实现?

谢谢!

reactjs tooltip
1个回答
0
投票

您需要的是popoverhere is an example。您可以在互联网上找到一些内容,但也很容易重新创建它:

。ts:

import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";

const App = () => {
  const [isPopoverVisible, setPopoverVisibility] = React.useState(false);

  const togglePopover = () => {
    setPopoverVisibility(!isPopoverVisible);
  };

  return (
    <>
      <Popover isVisible={isPopoverVisible}>
        <button onClick={() => togglePopover()}>coucou</button>
      </Popover>
      <div>other content</div>
    </>
  );
};

const Popover = ({ children, isVisible }) => {
  const childrenRef = React.createRef();
  const classes = `popover ${isVisible ? 'pop' : ''}`;

  return (
    <div className="popover-component">
      <span>{children}</span>
      <div className={classes}>This is the popover</div>
    </div>
  );
};

render(<App />, document.getElementById("root"));

。css:

.popover-component{
  position: relative;
}
.popover{
  display: none;
  position: fixed;
  background-color: #FFF;
  border: 1px solid black;
  border-radius: 4px;
  padding: 5px;
}

.pop {
  display: block;
}

Here is the repro on stackblitz。然后,您可以通过获取孩子的宽度并玩耍来调整弹窗(例如通过更改算法来重新创建选项“顶部”,“底部”,“左”,“右”)。

© www.soinside.com 2019 - 2024. All rights reserved.