点击滚动到评论内容位置
目标:能够在点击评论图标时滚动到评论内容位置
分析说明:
步骤:
- 创建获取评论区域DOM的 ref 对象
- 获取到评论相对于页面顶部的高度,来跳转到相应位置
核心代码:
article/index.tsx 中:
/**
* 导航栏高度的常量
*/
const NAV_BAR_HEIGTH = 45
const Article = () => {
//获取评论区的dom
const commentRef = useRef<HTMLDivElement>(null)
const isShowComment = useRef(false)
// 展示 or 隐藏评论内容
const onShowComment = () => {
//防止为获取到dom
//全屏的dom
const wrapper = wrapperRef.current
if (!wrapper) return
//评论区的dom
const comment = commentRef.current
if (!comment) return
//getBoundingClientRect是dom自带的属性
const commentTop = comment.getBoundingClientRect().top
// console.log(commentTop)
if (!isShowComment.current) {
// 还没有展示评论信息,此时,就展示评论信息
wrapper.scrollTo({
// wrapper.scrollTop 表示已经滚动的距离
top: commentTop - NAV_BAR_HEIGTH + wrapper.scrollTop,
// 如果想要滚动时,带有动画效果,可以使用 smooth 即可
behavior: 'auto'
})
isShowComment.current = true
} else {
// 已经展示评论信息,此时,需要返回页面顶部
wrapper.scrollTo(0, 0)
isShowComment.current = false
}
}
const renderArticle = () => {
return (
// ...
<div className="comment" ref={commentRef}></div>
)
}
return (
// ...
<CommentFooter onShowComment={onShowComment} />
)
}
article/components/CommentFoot