社区精选|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/

随时掌握互联网精彩
- AI-Media2Doc一键音视频转文档,支持主流自媒体平台图文风格转换!
- 欧盟宣布成立“关键药物联盟”
- 大数据、人工智能和机器学习:竞选活动的范式转变
- 韩元汇率对人民币2024年1月3日
- 【有料视频】怎么给Steam换皮肤?
- 预算2000以内,适合买给学生用的3款手机推荐
- 效仿Project Aria,谷歌将在公共场所测试AR眼镜原型机
- TA 家的零售数字化方案让ROI 提升28% !
- 1支雪糕20元?6颗话梅128元?七月起价格“刺客”将无处遁形
- Surface Hub 2 智能摄像头:视频会议 C 位指南
- 初代安卓系统公开发布;诺基亚更名为微软 Lumia;开放手持设备联盟成立 | 历史上的今天
- 【周末荐书】慢教授:做一只奔跑的蜗牛
赞助链接