在 ReactJS 上,无法处理从导航栏到页面中 div 的导航

on ReactJS, can't handle a navigation to a div in page from the navigation bar

我在处理一个项目时遇到问题,我需要在单击导航项时导航到页面的特定部分。

我正在按如下方式使用 Navlink 组件,但无法找到解决方案。

在我的导航组件 Toolbar.js 中,我有以下关于导航项的代码。

Toolbar.js

           <li>
            <NavLink
              exact
              activeStyle={{
                fontWeight: 'bold',
                color: 'red',
                textDecoration: 'none'
              }}
              to="/"
            >
              agence
            </NavLink>
          </li>

然后我在 Home.js 中使用如下组件:

Home.js

return (
      <Layout>
        <Toolbar drawerClickHandler={this.drawerToggleClickHandler} />
        <SideDrawer show={this.state.sideDrawerOpen} />
        {backDrop}
        <Conseil />
        <div className={classes.white}></div>
        <Sigles />
        <NotreAgence />
        <Prestations />
        <ScrollableMenu />
        <Form />
        <Footer />
      </Layout>
    );
  }

我想做的是在单击上面显示的 "accueil" NavLink 时导航到 "NotreAgence" 组件。

我试着模仿 html :

<a href="#scroll">Go to Title</a>
<div>
  <h1 id="scroll">Title</h1>
</div>

如下:

            <NavLink
              exact
              activeStyle={{
                fontWeight: 'bold',
                color: 'red',
                textDecoration: 'none'
              }}
              to={{
                pathname: '/',
                hash: '#our-agency'
              }}
            >
              agence
            </NavLink>

并为 div 标签提供“#our-agency”标签。

但是好像不行。

我有点卡住了。有什么帮助吗?

非常感谢:)

to={{
  pathname: '/',
  hash: '#our-agency'
}}

当您在 link 中有 / 时 - 它会强制更新页面。 因此,如果您想到达当前页面上的部分,您只需要使用

to="#our-agency"

快速更新以解决此问题。一种解决方案是使用 react-scroll 库。

在导航中 menu/bar: 导入 => import { Link } from 'react-scroll'

定义您的导航项如下(使用问题的代码使其更清楚):

Toolbar.js

import { Link } from 'react-router' 


(...)   


          <li>
            <Link
              exact
              activeStyle={{
                fontWeight: 'bold',
                color: 'red',
                textDecoration: 'none'
              }}
              to="notreAgence"
            >
              agence
            </Link>
          </li>

为您的组件提供一个 id 道具,其值与 Link 中的 to 道具相匹配。 (此处为 'section1'。

Home.js

return (
  <Layout>
    ...
    <NotreAgence id='notreAgence' />
    ...
  </Layout>
);

}

这就成功了。

更多信息:https://scotch.io/tutorials/implementing-smooth-scrolling-in-react