位置工具提示 div,跨度上方可变高度(反应)

Position Tooltip div with variable height above span (React)

我正在尝试构建一个工具提示,它会出现在某些文本中的单词上方。如果工具提示 div 始终具有相同的高度,则效果很好。但有时我想在里面放很多文字或其他东西,有时它可能是一个单行句子。

我对如何在此处编写定位代码感到困惑,因为为此我需要工具提示的高度?我希望工具提示 div 始终在目标词上方居中,并且我希望工具提示的宽度和高度完全可变,并且永远不会与目标词重叠。

到目前为止我得到的是:

const wordWithToolTip = ({ word, tooltip }) => {

    return (
        <div
            style={{ display: 'inline-block', position: 'relative', border: '2px solid red' }}
            
            onMouseEnter={() => setShowTranslation(true)}
            onMouseLeave={() => setShowTranslation(false)}>

            {showTranslation && (
                <div
                    style={{
                        position: 'absolute',
                        top: '-30px', //this works fine, but I cannot assume that 30px will always suffice. If the tooltip div gets really big, -30px won't do anything and it will overlap the word and look off. Ideally, I'd have something that says: always appear 10px above the word, and go as high as you want, but never below those 10px etc.
                        padding: '2px',
                        border: '2px solid black',
                        backgroundColor: 'white',
                    }}>
                    {tooltip}
                </div>
            )}
            <span>{word}</span>
        </div>
    );
};

为此,您需要为工具提示元素的高度设置状态,然后相应地调整 top css 属性。像这样的东西会起作用:

const wordWithToolTip = ({ word, tooltip }) => {

const [height, setHeight] = useState("");
const tooltipEl = useRef(null);

useEffect(() => {
   const refheight = tooltipEl.current.offsetHeight;
   setHeight({ refheight });
}, []);

return (
    <div
        style={{ display: 'inline-block', position: 'relative', border: '2px solid red' }}
        
        onMouseEnter={() => setShowTranslation(true)}
        onMouseLeave={() => setShowTranslation(false)}>

        {showTranslation && (
            <div
                ref={tooltip}
                style={{
                    position: 'absolute',
                    top: '-' + height+10 + 'px', //You'll have to adjust this accordingly. 
                    padding: '2px',
                    border: '2px solid black',
                    backgroundColor: 'white',
                }}>
                {tooltip}
            </div>
        )}
        <span>{word}</span>
    </div>
);
};

10 代表您从工具提示到单词的边距。