[英]Render HTML with <script> tag inside a component in REACT
[英]React : navigate to a html tag inside a component
我想從一個組件到另一個組件的 go 並直接滑動到其中的 html 標簽。
使用反應路由器 v6
<Route path="/mypage/#c" element = {<MyPage/>} />
(#c 是 /mypage 中 html 標記的 id)
但我提供的代碼不起作用。
它只是進入頁面而不是滑入標簽。
hash 應該添加到鏈接中,或者只是從 URL 中讀取,即location
object,而不是在Route
組件的path
屬性上指定。 將其添加到path
將破壞路由路徑匹配。
<Route path="/mypage" element={<MyPage />} />
react-router-dom@6
不處理直接鏈接到文檔中的哈希標簽,目前最好的庫在以前版本的 RRD 中執行此操作, react-router-hash-link
尚未更新支持 RRDv6。
MyPage
組件可以使用依賴於location.hash
的useEffect
掛鈎,查詢 DOM,並嘗試將該元素滾動到視圖中。
例子:
import { useLocation } from "react-router-dom";
const MyPage = () => {
const { hash } = useLocation();
useEffect(() => {
const el = document.querySelector(hash);
if (el) {
el.scrollIntoView({ behavior: "auto" });
}
}, [hash]);
return (
<>
... content ...
<div id="c">This is the content I'm interested in</div>
... more content ...
</>
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.