[英]on ReactJS, can't handle a navigation to a div in page from the navigation bar
我在一個項目中遇到了問題,當單擊導航項時,我需要導航到頁面的某個部分。
我正在使用 Navlink 組件,如下所示,無法找到解決方案。
在我的導航組件 Toolbar.js 中,我有以下關於導航項的代碼。
工具欄.js
<li>
<NavLink
exact
activeStyle={{
fontWeight: 'bold',
color: 'red',
textDecoration: 'none'
}}
to="/"
>
agence
</NavLink>
</li>
然后我在 Home.js 中使用如下組件:
主頁.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'
}}
當你有 / in 鏈接時 - 它會強制更新頁面。 因此,如果您想訪問當前頁面上的部分,則只需使用
to="#our-agency"
快速更新以關閉此問題。 一種解決方案是使用react-scroll
庫。
在導航菜單/欄中: import it => 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.