主頁中的 React Router 目標 div id (React Router target div id in home page)


問題描述

主頁中的 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.

  1. Run npm i react‑router‑hash‑link on your project.
  2. Replace <Link className="nav‑link text‑white font‑weight‑bold" to={{ pathname: "/", hash: "#about" }} data‑target="#about"> About</Link>
  3. With <HashLink to="/#about">About</HashLink>

(by pzero1STEPS)

參考文件

  1. React Router target div id in home page (CC BY‑SA 2.5/3.0/4.0)

#url #reactjs #react-router #github-pages #react-router-dom






相關問題

正則表達式查找和替換 url 不起作用或如何使其起作用 (Regex to Find and Replace url does not work or how to make it work)

子網站的 URL 重寫? (URL Rewriting for a Subsite?)

使用 htaccess 從基本 URL 中刪除變量 (Remove variable from base URL with htaccess)

在 URL 地址中使用項目名稱而不是 ID (Using item's name in the URL address instead of IDs)

Perl Chèn chuỗi vào url tại các địa điểm cụ thể (Perl Inserting string into a url at specific places)

Cách ẩn mọi thứ sau tên trang web của bạn bằng .htaccess (How to hide everything after your webpage name with .htaccess)

在 gwt 框架中使用參數更改 url (Changing url with parameters in gwt framework)

用於 SEO 目的的 Nodejs URL 修改 (Nodejs URL modifications for SEO purposes)

將用戶重定向到外部站點 (Redirecting user to external site)

Python 循環遍歷 csv 文件中的 url 返回 \ufeffhttps:// (Python Looping through urls in csv file returns \ufeffhttps://)

主頁中的 React Router 目標 div id (React Router target div id in home page)

.htaccess https、www 和子域靜默重寫 (.htaccess https, www and subdomain silent rewrite)







留言討論