使用useRef反应滚动导航

朱利安

我正在尝试制作一个单页应用程序,在其中单击链接,它向下滚动到与菜单项相对应的部分。我花了几天时间研究适合我的标准的修复程序,但不幸的是,我的运气很少。

我的标准如下:

  • 没有外部依赖
  • 地址栏中必须有网址(以允许直接链接到特定部分)
  • 一定不要骇客(例如将网址插入网址列)
  • 必须尽可能简单

我希望不要要求太多。

您可以在这里使用我的CodeSandbox进行游戏叉感谢!

德鲁·里斯(Drew Reese)

您可以使用forwardRefHOC包装每个部分ref为每个部分创建并设置一个,然后将ref传递给标头组件,以便它可以在其上调用该scrollIntoView函数。

编辑添加了一个效果来查看位置并触发滚动。

const Header = ({ refs }) => {
  const location = useLocation();

  useEffect(() => {
    console.log("location", location.pathname);
    switch (location.pathname) {
      case "/about":
        scrollSmoothHandler(refs.aboutRef);
        break;
      case "/contact":
        scrollSmoothHandler(refs.contactRef);
        break;
      case "/hero":
        scrollSmoothHandler(refs.heroRef);
        break;

      default:
      // ignore
    }
  }, [location, refs]);

  const scrollSmoothHandler = ref => {
    console.log("Triggered.");
    ref.current.scrollIntoView({ behavior: "smooth" });
  };

  return (
    <>
      <NavLink to="/hero" activeClassName="selected">
        Hero
      </NavLink>
      <NavLink to="/about" activeClassName="selected">
        About
      </NavLink>
      <NavLink to="/contact" activeClassName="selected">
        Contact
      </NavLink>
    </>
  );
};

const Hero = forwardRef((props, ref) => {
  return (
    <section ref={ref}>
      <h1>Hero Section</h1>
    </section>
  );
});

const About = forwardRef((props, ref) => {
  return (
    <section ref={ref}>
      <h1>About Section</h1>
    </section>
  );
});

const Contact = forwardRef((props, ref) => {
  return (
    <section ref={ref}>
      <h1>Contact Section</h1>
    </section>
  );
});

function App() {
  const heroRef = useRef(null);
  const aboutRef = useRef(null);
  const contactRef = useRef(null);

  return (
    <div className="App">
      <HashRouter>
        <Header refs={{ aboutRef, contactRef, heroRef }} />
        <Hero ref={heroRef} />
        <About ref={aboutRef} />
        <Contact ref={contactRef} />
      </HashRouter>
    </div>
  );
}

编辑forwardRef和scrollIntoView

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章