在浏览器中打开 URL 时响应滚动到锚点

Sal*_*ooo 7 html javascript reactjs

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

/post/:postId/#commentId
Run Code Online (Sandbox Code Playgroud)

我已经在工作 postId 路线/post/:postId

我尝试使用react-hash-link npm 包来实现它,但它没有按预期工作。

每个评论都有自己的 ID,该 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>
Run Code Online (Sandbox Code Playgroud)

例如,如果我打开如下 URL:

/post/postId/#5d2775ecdd51be1858f6b753 
Run Code Online (Sandbox Code Playgroud)

我想打开帖子页面,并且它向下滚动到带有 # 锚点的评论。

有没有办法实现这个?

Sal*_*ooo 3

我设法为我的用例找到简单的解决方案,无需创建注释引用、传递它们等。因为我的组件层次结构如下:

  1. Post--> 渲染组件Comments
  2. Comments--> 渲染多个组件Comment使用传递过来的 props 数据渲染多个组件Post

Post组件中我创建了函数:

scrollToComment= () => {
    let currentLocation = window.location.href;
    const hasCommentAnchor = currentLocation.includes("/#");
    if (hasCommentAnchor) {
      const anchorCommentId = `${currentLocation.substring(currentLocation.indexOf("#") + 1)}`;
      const anchorComment = document.getElementById(anchorCommentId);
      if(anchorComment){
          anchorComment.scrollIntoView({ behavior: "smooth" });
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

然后我渲染Comments这样渲染:

<Comments limit={limit} post={post} scrollToComment={this.scrollToComment} />
Run Code Online (Sandbox Code Playgroud)

Comments我像这样排序后生成评论:

{sortedComments.map((comment, i) => <Comment key={i} {...comment} scrollToComment={this.props.scrollToComment}/> )}
Run Code Online (Sandbox Code Playgroud)

最后在Comment我执行的组件中scrollToComment组件中ComponentDidMount()

if(this.props.scrollToComment)
    this.props.scrollToComment(this.props._id);
Run Code Online (Sandbox Code Playgroud)

之后,当我访问某个 URL 时,我可以很好地平滑滚动到 URL 的哈希部分中指定的注释。

我尝试了@Christopher 解决方案,但它对我不起作用。