导航到主页并在单击其他页面的菜单项时滚动到部分 id

问题描述 投票:0回答:1

我有一个单页登陆主页,其中包含带有 id 的组件和跨所有页面的通用菜单。当我打开/我使用react-scroll向下滚动到特定部分时。但是当我单击 /home 之外的菜单时,它应该首先重定向到 / 然后滚动到单击的部分 id 。

  return (
        <Navbar collapseOnSelect expand="lg" bg="white" variant="white" >
            <Container>
                
                <Navbar.Brand href="/home"> <img src={images.logo} alt="logo" /></Navbar.Brand>
                <Navbar.Toggle aria-controls="responsive-navbar-nav" />
                <Navbar.Collapse id="responsive-navbar-nav" className="justify-content-end"  >
                    <Nav>
                        {data.Menu.map((item, index) => (
                
                                <ScrollLink key={index} to={item.link} smooth={true} duration={100} offset={-100} className="nav-link">{t(item.text)} </ScrollLink>
                           
                        ))}
                    </Nav>

我尝试了窗口 href 重定向,但该组件仅被重定向到主页,没有滚动。

the data file 
const Menu = [
    {
        text: "Home",
        link: "home",
    },
    {
        text: "About Us",
        link: "about-us",
    },
reactjs react-hooks frontend react-bootstrap
1个回答
0
投票

尝试这样的事情:

import { useNavigate } from "react-router-dom";

function Nav() {
    const navigate = useNavigate();

    return (
        <>
             <div onClick={() => {
                 navigate('/page', {
                     state: {
                         section: 1 // sets variable to 1 and passes to linked page
                     }
                 })
             }>
             </div>
             <div onClick={() => {
                 navigate('/page', {
                     state: {
                         section: 2 // sets variable to 2 and passes to linked page
                     }
                 })
             }>
             </div>
         </>
    )
}

import { useState } from "react";
import { useLocation } from 'react-router-dom';

function Page() {
    const location = useLocation();
    const [ scrolled, setScrolled ] = useState(false);
    
    if (!scrolled) { // prevents infinite loop
        switch (location.state.section) { // scrolls to page based on section
             case 1: window.scrollTo({ top: 0, behavior: "smooth" }); break;       case 2: window.scrollTo({ top: 1000, behavior: "smooth" }); break; 
        setScrolled(true);
    }

    return( <> </> )
}
© www.soinside.com 2019 - 2024. All rights reserved.