简体   繁体   English

如何从一个组件滚动到另一个组件的元素?

[英]how to scroll from one component to an element of another component?

I have 2 components, Component A and Component B which are rendered in the same page.我有 2 个组件,即组件 A 和组件 B,它们在同一页面中呈现。 What I need is to scroll to a div of the Component B once I click on a button in the Component A.我需要的是在单击组件 A 中的按钮后滚动到组件 B 的 div。

Component B: B组份:

import React, { FC, useRef } from 'react';

const Footer: FC<Props> = ({ children }) => {
const commentSection = useRef(null);
const gotoCommentSection = () => window.scrollTo({top: commentSection.current.offsetTop, behavior: "smooth"})

  return (
    <>
      <div className="footerClass" ref={commentSection}>
        <div className="container">{children}</div>
      </div>
    </>
  );
};

export default Footer;

if I insert this button in Component B, the scrolling function is working.如果我在组件 B 中插入此按钮,则滚动 function 正在工作。 But how can I achieve that from the Component A?但是我怎样才能从组件 A 中实现呢?

 <button type="button" onClick={gotoCommentSection}>Scroll to Area</button>

I think it will work to move useRef up the component tree to Component A along with your scroll function.我认为将 useRef 向上移动组件树到组件 A 以及滚动 function 将起作用。 Then use React.forwardRef to apply that ref to the element in Component B. Looks like this is a decent example: https://stackoverflow.com/a/49832065/9325243然后使用 React.forwardRef 将该引用应用于组件 B 中的元素。看起来这是一个不错的示例: https://stackoverflow.com/a/49832065/9325243

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM