簡體   English   中英

反應:導航到組件內的 html 標記

[英]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.hashuseEffect掛鈎,查詢 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 ...
    </>
  );
};

編輯 react-navigate-to-a-html-tag-inside-a-component

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM