react中,点击滚动到相应的位置

点击滚动到评论内容位置

目标:能够在点击评论图标时滚动到评论内容位置

分析说明

参考:MDN getBoundingClientRect

参考:MDN scrollTo()

步骤

  1. 创建获取评论区域DOM的 ref 对象
  2. 获取到评论相对于页面顶部的高度,来跳转到相应位置

核心代码

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值