社区精选|React 制作全局 Tooltip 文字提示组件
今天小编为大家带来的是社区作者 Awbeci 的文章,让我们一起来学习用 React 制作全局 Tooltip 文字提示组件。
前言
操作
1、创建一个悬浮的 dom div,并且设置一下基本样式且是隐藏状态
const tooltipRef = useRef(null)
const [content, setContent] = useState(null)
<div className={styles.tooltip} ref = {tooltipRef }>
{content}
</div>
.tooltip{
display: flex;
position: fixed;
align-items: center;
justify-content: center;
height: 34px;
width: 170px;
background-color: #000;
color: #fff;
visibility: hidden;
z-index: 100;
border-radius: 6px;
font-size: 12px;
}
// 制作三角箭头
.tooltip::after {
content: " ";
position: absolute;
top: 100%; /* At the bottom of the tooltip */
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: black transparent transparent transparent;
}
`// 鼠标移开
onMouseLeave={(e,value,currentDate) => {
// 鼠标移开的时候要隐藏 tooltip
tooltipRef.current.style = `visibility:hidden;`
}}
// 鼠标进入
onMouseOver={(e, value, currentDate)=>{
// 获取你的 dom 元素距离窗口的 left 和 top,这个 left 和 top 就是你 tooltip 相对的位置
const { left, top } = e.currentTarget.getBoundingClientRect();
// 有了 left 和 top 我们设置 tooltip 的位置,并且要设置 visibility 为显示状态
tooltipRef.current.style = `visibility:visible;top:${top-42}px;left: ${left-79}px`
if (!value || !value.date) {
setCalContent(`提交 0 次,${currentDate}`)
}else{
setCalContent(`提交 ${value.count} 次,${value.date}`)
}
}}`
onMouseOver 的使用就是鼠标移动到上面的时候
2.1、首先获取元素的位置坐标信息
const { left, top } = e.currentTarget.getBoundingClientRect();
2.2、有了坐标我们就要让 tooltip 显示到那里
tooltipRef.current.style = `visibility:visible;top:${top-42}px;left: ${left-79}px`
2.3、并且设置显示的内容
setCalContent(xxxx)

总结
2、最重要的一点其实是如何获取被提示组件或者元素的位置坐标信息,所以e.currentTarget.getBoundingClientRect()代码非常重要。
3、有了坐标就可以设置 tooltip 要显示的位置了,不过还需要手动调整一下,top:${top-42}px;left: ${left-79}px。
引用
getBoundingClientRect:https://github.com/facebook/react/issues/16201
MDN getBoundingClientRect:https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect


关注公众号:拾黑(shiheibook)了解更多
赞助链接:
关注数据与安全,洞悉企业级服务市场:https://www.ijiandao.com/
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/

随时掌握互联网精彩
- 美元兑人民币汇率2024年6月4日
- 新一届手机颜王诞生?魅族21真机亮相
- “我用 ChatGPT 造了一个零日漏洞,成功逃脱了 69 家安全机构的检测!”
- 微软与上海徐汇区深化战略合作,赋能上海科技生态
- 始于共建,盛于共享:“铁塔模式”成国企改革标杆
- “无线电与和平”(Radio and Peace)——第十二个“世界无线电日”
- 造车新势力角逐战:“蔚小理”不断内卷,“哪零威”攻势凶猛
- 中国广电启动首批20省5G服务试商用
- 微软智能云在华发布多项混合云服务及功能更新
- 浙江移动默认关闭接听国际电话:为防境外电话诈骗!
- 【大公司创新情报】华为计划年底拓展1000家体验店卖车
- 美国网络安全与基础设施安全局发布《CISA全球参与》文件
赞助链接