首页 > 解决方案 > React - 如何跟踪用户在页面上的当前位置?

问题描述

我有一个单页网站,每次点击导航项都会滚动到不同的部分。目前,如果我从其中一个部分滚动,导航栏是不知道的,并且不允许滚动到先前单击的部分。

我希望能够跟踪用户在页面上的位置并让导航栏做出相应的响应。

所有的应用程序组件都在这里呈现:

function App() {
  const homeRef = useRef();
  const aboutRef = useRef();
  const portRef = useRef();
  const contactRef = useRef();
  const [selection, setSelection] = useState("home");
  const handleSelect = (select) => {
    setSelection(select);
  };
  useEffect(() => {
    if (selection === "home") {
      homeRef.current.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
    }
    if (selection === "about") {
      aboutRef.current.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
    }
    if (selection === "portfolio") {
      portRef.current.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
    }
    if (selection === "contact") {
      contactRef.current.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
    }
  },[selection]);
  return (
    <div className="allShared">
      <Navigation className="nav" onNavSelection={handleSelect}></Navigation>
      <div ref={homeRef}>
        <Home></Home>
        </div>
        <div ref={aboutRef}>
        <About></About>
        </div>
        <div ref={portRef}>
        <Portfolio></Portfolio>
        </div>
        <div ref={contactRef}>
        <Contact></Contact>
        </div>
    </div>
  );
}

export default App;

子组件将单击哪个导航项传递给父组件。

const Navigation = (props) => {
  const sendData = (key) =>{
    props.onNavSelection(key)
  }
  return (
    <Navbar
      className="nav "
      collapseOnSelect
      expand="lg"
      fixed="top"
      bg="dark"
      variant="dark"
      style={{
        opacity: "0.9",
      }}
    >
      <Navbar.Toggle aria-controls="responsive-navbar-nav" />
      <Navbar.Collapse id="responsive-navbar-nav">
        <Nav className="mr-auto mr-5" onSelect={(selectedKey)=>sendData(selectedKey)}>
          <Nav.Link eventKey="home">Home</Nav.Link>
          <Nav.Link eventKey="about">About</Nav.Link>
          <Nav.Link eventKey="portfolio">Portfolio</Nav.Link>
          <Nav.Link eventKey="contact">Contact</Nav.Link>
          <Nav.Link target="_blank" href="">CV</Nav.Link>
        </Nav>
      </Navbar.Collapse>
    </Navbar>
  );
};

export default Navigation;

任何指针和提示表示赞赏。

标签: javascriptreactjs

解决方案


您可以创建自己的自定义挂钩来跟踪页面滚动坐标

import { useState, useEffect } from 'react';

export default () => {
  const [scrollPosition, setScrollPosition] = useState(null);
  useEffect(() => {
    const handleScroll = () => setScrollPosition(window.scrollY);
    document.addEventListener('scroll', handleScroll);
    return () => 
      document.removeEventListener('scroll', handleScroll);
  }, []);
  return scrollPosition;
}

然后在组件中使用它

import React from 'react';
import useBodyScrollPosition from './use-body-scroll-position';

export default () => {
  const scrollPosition = useBodyScrollPosition();
  const wrapperStyles = {
    height: '5000px',
  };
  const displayStyles = {
    position: 'fixed',
    width: '100%',
    top: '50%',
    transform: 'translateY(-50%)',
    fontSize: '20px',
    textAlign: 'center',
  }
  return (
    <div style={wrapperStyles}>
      <div style={displayStyles}>
        {scrollPosition !== null ? scrollPosition : 0}
      </div>
    </div>
  )
}

我正在搜索自定义钩子,我记得这件事。从原作者那里检查: https ://dev.to/wellpaidgeek/how-to-write-custom-hooks-in-react-1ana


推荐阅读