![](/img/trans.png)
[英]how to detect the scroll reaches the specific component in react js using ref
[英]How to scroll to a specific component in React JS
我已经使用 React(没有任何 HTML)构建了一个网站,并且我已经将每个页面拆分为更小的组件。 假设我有例如主页,并且在第一个组件(位于页面顶部的主要部分)中有一个按钮,当我单击它时,我希望它带我到最后一个页面的组件(位于最底部)。 我想要类似于 HTML “点击滚动到 ID 元素”的东西。
我怎样才能做到这一点? 请记住,我为每个组件创建了一个单独的 js 文件。
谢谢!
您可以使用反应挂钩来实现它。 您必须稍微重构最后一个组件以转发ref
。 您可以使用useImperativeHandle钩子在LastComp
中公开滚动方法。
const LastComp = forwardRef((props, ref) => {
const compRef = useRef();
useImperativeHandle(ref, () => ({
// expose the method to the forwarded ref
scrollIntoView: () => {
compRef.current.scrollIntoView({ behavior: "smooth", block: "start" });
}
}));
return (
<div style={{ height: "600px", backgroundColor: "gray" }} ref={compRef}>
Body of the last component
</div>
);
});
在主页上,您可以将新的 ref 传递给LastComp
并将滚动方法添加为按钮事件处理程序。
import { useImperativeHandle, forwardRef, useRef } from "react";
export default function Main() {
const ref = useRef(null);
// event handler for the button
const scrolltoLast = () => {
if (ref.current) {
ref.current.scrollIntoView();
}
};
return (
<div className="App">
<button onClick={scrolltoLast}>Scroll to Last</button>
<div
style={{
height: "600px",
backgroundColor: "tomato"
}}
>
First
</div>
<div style={{ height: "600px", backgroundColor: "lightblue" }}>
Second
</div>
<LastComp ref={ref} />
</div>
);
}
组件的位置无关紧要,它可以在主页的任何位置。 当您单击按钮时,它将滚动到要查看的组件(使用scrollIntoView )。
添加指向页面元素的链接
<Link to="/page#elementid">Go</Link>
在你的页面组件中这样做
componentDidMount() {
let target = window.location.hash;
target && document.querySelector(target).scrollIntoView()
}
您必须通过唯一的 id 来命名每个组件。
让 scroll_to = document.getElementById("conponent_id").offsetTop; window.scrollTo({行为:“平滑”,顶部:scroll_to,});
onclick 按钮只需运行此代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.