javascript - 在浏览器中打开 URL 时 react 滚动到 anchor

标签 javascript html reactjs

假设我有组件“Post”,它包含多个组件“Comment”。当我输入这样的 URL 时,我想让该应用程序在带有该 anchor 的评论上向下滚动:

/post/:postId/#commentId

我已经在工作 postId route /post/:postId
我尝试使用 react-hash-link npm 包来实现它,但它没有按预期工作。

每条评论都有自己的 ID,在组件上设置,如下所示:
<div class="post">
   <div class="post-header">
      <div class="post-header-avatar">
        SOME TEXT
      </div>
      <div class="post-header-info">
        SOME TEXT
      </div>
   </div>
   <div class="post-content">
      <span>POST CONTENT</span>
   </div>
   <div class="post-likers-container">
      <div class="post-likers-header label">People who like this post</div>
      <div class="post-likers">
          SOME TEXT
      </div>
   </div>
   <div class="post-comments">
      <div class="comments ">
         <div class="comments-all label">Comments</div>
         <div class="comments">
            <div class="comment" id="5d27759edd51be1858f6b6f2">
               <div class="comment-content">
               COMMENT 1 TEXT
               </div>
            </div>
            <div class="comment" id="5d2775b2dd51be1858f6b720">
               <div class="comment-content">
               COMMENT 2 TEXT
               </div>
            </div>
            <div class="comment" id="5d2775ecdd51be1858f6b753">
               <div class="comment-content">
                COMMENT 3 TEXT
               </div>
            </div>
         </div>
      </div>
   </div>
</div>

因此,例如,如果我打开如下 URL:
/post/postId/#5d2775ecdd51be1858f6b753 

我想打开帖子页面,它会向下滚动到带有#anchor 的评论。

有什么方法可以实现吗?

最佳答案

我真的很喜欢你的解决方案@SaltyTeemooo。受此启发,我发现了一种更简单的方法,无需任何回调。
我的设置非常相似,所以可以说我正在处理帖子和评论。
Post我像这样创建评论(简化)并传递anchorId:

<Comments anchorId={window.location.href.slice(window.location.href.indexOf("#") + 1)} props... />
Comments我将 anchor id 传递到 Comment.js
<Comment anchorId={props.anchorId} props.../>
然后在 Comment ,我将当前元素滚动到 View 中,如果它是链接的元素
import React, { useRef, useEffect } from 'react';

function Comment () {

    const comment = useRef(null); //to be able to access the current one

    useEffect(() => {
        if(props.anchorId === props.commentData.id)
        {
            comment.current.scrollIntoView({ behavior: "smooth" });
        }
    }, []) //same as ComponentDidMount

    
    return(
       <div id={props.commentData.id} ref={comment}> //here is where the ref gets set
           ...
       </div>
    )
}

关于javascript - 在浏览器中打开 URL 时 react 滚动到 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57002519/

相关文章:

javascript - Backbone 应用程序未定义错误

javascript - 连接 2 个 svg 元素

reactjs - 使用 React 的 Webpack 4 配置

android - 如何在 React Native 中使用 ListView 获得跑马灯效果?

javascript - 如何使用ajax函数发送表单而不刷新页面,我错过了什么?我必须为此使用rest-framework吗?

javascript - 更新 ReactJS 状态数组

javascript - carousell 每个 div 都做一些其他的事情 onclick

html - 当文本太长时跨度错位

css - 列表项之间的间距不规则

javascript - React js 中的表单提交