React更改视图并滚动到元素

4
我想要从一个视图链接到另一个视图并滚动到特定元素。我不需要任何动画,只希望该元素在视图中可见。从一个视图链接到另一个视图是通过React路由完成的。
我猜我可以在我想要滚动到的元素上创建引用,并将它们传递给其他视图,但不知道这是否是正确的方法?
以下是一个简单的示例。(不能工作,但希望您能理解我想要实现的内容)
const ViewOne = () => {
  const navigate = useNavigate(); // From react-router v6
  return (
    <p onClick={() => 
    {
      navigate("ViewTwo"); 
      // What more do I have to add? 
    }}>
      Link to section two, in view two
    </p>
  );
}

export default ViewOne;

const ViewTwo = () => {
return (
  <>
    <section style={{height: "100vh"}}></section>
    <section style={{height: "100vh"}}>
      Scroll here?
    </section>
    <section style={{height: "100vh"}}></section>
  </>);
}
export default ViewTwo;

我正在使用 react-router-dom-v6

2个回答

4

指定你想要滚动到的部分,并查找其 id 属性。在路由状态中传递一个目标 id。使用 useEffect 钩子来定位元素并将其滚动到视图中。

示例:

const ViewOne = () => {
  const navigate = useNavigate(); // From react-router v6
  return (
    <p
      onClick={() => {
        navigate("/viewtwo", { state: { targetId: "section2" } });
      }}
    >
      Link to section two, in view two
    </p>
  );
};

...

const ViewTwo = () => {
  const { state } = useLocation();
  const { targetId } = state || {};

  useEffect(() => {
    const el = document.getElementById(targetId);
    if (el) {
      el.scrollIntoView();
    }
  }, [targetId]);

  return (
    <>
      <section id="section1" style={{ height: "100vh" }}></section>
      <section id="section2" style={{ height: "100vh" }}>
        Scroll here?
      </section>
      <section id="section3" style={{ height: "100vh" }}></section>
    </>
  );
};

...

<Router>
  <Routes>
    ...
    <Route path="/viewone" element={<ViewOne />} />
    <Route path="/viewtwo" element={<ViewTwo />} />
    ...
  </Routes>
</Router>

Edit react-change-view-and-then-scroll-to-element


很好很简明的回答!喜欢它,而且它完美地起作用! - Awshaf Ishtiaque

1

你可以使用"useRef"在点击事件中滚动到该位置,或者尝试使用"useEffect"在组件渲染后滚动到该位置。

const ViewTwo = () => {
    const scroller = useRef(null)
    const executeScroll = () => scroller.current.scrollIntoView()    

    return (
      <>
        <section style={{height: "100vh"}}></section>
        <section ref={scroller} style={{height: "100vh"}}>
          Scroll here?
        </section>
         <button onClick={executeScroll}> Click to scroll </button> 
        <section style={{height: "100vh"}}></section>
      </>);
    }
    export default ViewTwo;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接