社区精选|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年2月13日
- 澳元兑换人民币汇率2023年9月18日
- 中国—东盟信息港打造“数字丝绸之路”
- 真我GT Neo3评测:150W加持,不仅仅是合格换代产品
- 2021操作系统生态大会将在京召开
- 2022微软“创新杯”绝密档案发布,技术PK来赢大奖!
- 假货猖狂,倒爷赚翻:卡脖之外的中国“芯”酸
- 【大公司创新情报】华为计划年底拓展1000家体验店卖车
- 云网融合为啥这么火?
- 盘点2020之5G标准:R16标准冻结完善能力三角,开启商用“新纪元”
- 小米 11 不送充电器;苹果已修复 iCloud 登录激活问题;Ruby 3.0.0 发布|极客头条
赞助链接