繁体   English   中英

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

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

我有 2 个组件,即组件 A 和组件 B,它们在同一页面中呈现。 我需要的是在单击组件 A 中的按钮后滚动到组件 B 的 div。

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;

如果我在组件 B 中插入此按钮,则滚动 function 正在工作。 但是我怎样才能从组件 A 中实现呢?

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

我认为将 useRef 向上移动组件树到组件 A 以及滚动 function 将起作用。 然后使用 React.forwardRef 将该引用应用于组件 B 中的元素。看起来这是一个不错的示例: https://stackoverflow.com/a/49832065/9325243

暂无
暂无

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

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