問題描述
主頁中的 React Router 目標 div id (React Router target div id in home page)
我正在使用反應路由器,特別是 HashRouter,因為我試圖在 github 頁面上託管我的反應應用程序。在使用 HashRouter 之前,我只是使用 BrowserRouter,我能夠在默認(Home)路由上定位特定 div(即 ;)
通過其 id 如下 ...
<li className="nav‑item">
<a
className="nav‑link text‑white font‑weight‑bold"
href="/#about"
data‑target="#about"
>
About
</a>
</li>
上面的工作完全符合我的希望,只需將主頁向下滾動到具有 id 的 About 部分:#about。但是,現在我正在使用 HashRouter 並且無法實現相同的期望行為。現在,當我單擊該鏈接時,它只會轉到 Home 組件,但不會像以前那樣滾動到 about 部分。有沒有簡單的解決方案來解決這個問題?我已經包含了下面相關代碼部分的片段...
<HashRouter basename="/">
<Switch>
<Route exact path="/" component={Home} />
<ContextProvider>
<Route
path="/terms‑and‑conditions"
component={TermsAndConditions}
/>
<Route path="/contact" component={Contact} />
<Switch>
<HashRouter>
<li className="nav‑item">
<Link
className="nav‑link text‑white font‑weight‑bold"
to={{ pathname: "/", hash: "#about" }}
data‑target="#about"
>
About
</Link>
</code></pre>
參考解法
方法 1:
Try this package React Router Hash Link. For more info on package, visit [react‑router‑hash‑link] 1 but the steps below should suffice.
- Run
npm i react‑router‑hash‑link
on your project.
- Replace
<Link className="nav‑link text‑white font‑weight‑bold" to={{ pathname: "/", hash: "#about" }} data‑target="#about"> About</Link>
- With
<HashLink to="/#about">About</HashLink>
參考文件