我有一個函式可以檢查頁面上是否存在 url 路徑名中提供的 id 字串,如果存在,我想跳轉到頁面上的那個 div。我已經能夠檢查 id 是否存在,但是我找不到從反應中的函式跳轉到 id 的方法。我嘗試使用 react-router-hash-link,但我看不到使這項作業的方法,我也嘗試過這個......
const navigate = useNavigate()
const func = id_string => {
navigate('#' id_string)
}
這并沒有像我希望的那樣跳轉到相關的 div,任何人有任何想法如何使這項作業?
uj5u.com熱心網友回復:
你可以使用普通的javascript來做到這一點
const func = id_string => {
document.querySelector(`#${id_string}`).scrollIntoView()
}
您實際上可以這樣做useEffect,因此您可以在頁面加載后立即滾動
useEffect(() => {
// get id from URL
const id = ....
document.querySelector(`#${id}`).scrollIntoView()
}, [])
uj5u.com熱心網友回復:
// method to jump to the desired element by using the element's id
const jumpToReleventDiv = (id) => {
const releventDiv = document.getElementById(id);
// behavior: "smooth" parameter for smooth movement
releventDiv.scrollIntoView({behavior: "smooth"});
}
在此處閱讀有關scrollIntoView方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/487436.html
