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



我有两个组件,组件A和组件B,它们在同一个页面中呈现。我需要的是滚动到组件B的一个div,一旦我点击组件a中的一个按钮。

组件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中插入此按钮,则滚动功能正在工作。但是我如何从组件A中实现这一点呢?

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

我认为它将工作移动useRef组件树到组件A与您的滚动功能。然后使用React。将该ref应用于组件b中的元素。看起来这是一个不错的例子:https://stackoverflow.com/a/49832065/9325243

最新更新