<a> 标签转到新页面,但没有转到新页面的顶部
<a> tag goes to new page, but does not go to the top of the new page
我正在做一个有多个页面的 gatsby-react 项目。在页眉和页脚上,我项目中的其他页面有 links。当我点击 link 时,URL 发生变化,浏览器加载新页面并正常呈现。
唯一的问题是新页面不是从顶部加载的。例如,如果我当前正在查看页面底部并单击 link,那么我希望被带到新页面的顶部。发生的事情是我被带到新页面,但我留在底部。这张图片应该能解释我的意思。
我 不 使用 GatsbyLinks,因为它们会导致项目出现问题,我使用 link 的普通 <a>
标签。
我可以向 <a>
标签添加任何可以强制转到页面顶部的内容吗?如果没有,那么我可以使用其他 linking 组件吗?
提前致谢!
scroll restoration 的过程由 Gatsby 自动处理,但是,使用锚链接 (<a>
) 进行内部导航(在 React 范围之外)可能会导致此类问题,因为它缓存的页面数据,但您没有使用内部导航来管理或恢复它。
也就是说,我建议在需要时使用 useScrollRestoration
挂钩:
import { useScrollRestoration } from "gatsby"
import countryList from "../utils/country-list"
export default function PageComponent() {
const ulScrollRestoration = useScrollRestoration(`page-component-ul-list`)
return (
<ul style={{ height: 200, overflow: `auto` }} {...ulScrollRestoration}>
{countryList.map(country => (
<li>{country}</li>
))}
</ul>
)
}
对于更全局的方法,您还可以使用 gatsby-browser.js
API,例如 onRouteUpdate
and shouldUpdateScroll
,两者都会在每次页面更改(导航)时触发:
exports.onRouteUpdate = () => {
if (typeof window !== `undefined`) { window.scrollTo(0, 0)}
}
exports.shouldUpdateScroll = args => {
return false;
};
默认情况下,shouldUpdateScroll
获取最后滚动的位置,理想情况下,只需更改并返回 false
它应该适用于您描述的场景。
我正在做一个有多个页面的 gatsby-react 项目。在页眉和页脚上,我项目中的其他页面有 links。当我点击 link 时,URL 发生变化,浏览器加载新页面并正常呈现。
唯一的问题是新页面不是从顶部加载的。例如,如果我当前正在查看页面底部并单击 link,那么我希望被带到新页面的顶部。发生的事情是我被带到新页面,但我留在底部。这张图片应该能解释我的意思。
我 不 使用 GatsbyLinks,因为它们会导致项目出现问题,我使用 link 的普通 <a>
标签。
我可以向 <a>
标签添加任何可以强制转到页面顶部的内容吗?如果没有,那么我可以使用其他 linking 组件吗?
提前致谢!
scroll restoration 的过程由 Gatsby 自动处理,但是,使用锚链接 (<a>
) 进行内部导航(在 React 范围之外)可能会导致此类问题,因为它缓存的页面数据,但您没有使用内部导航来管理或恢复它。
也就是说,我建议在需要时使用 useScrollRestoration
挂钩:
import { useScrollRestoration } from "gatsby"
import countryList from "../utils/country-list"
export default function PageComponent() {
const ulScrollRestoration = useScrollRestoration(`page-component-ul-list`)
return (
<ul style={{ height: 200, overflow: `auto` }} {...ulScrollRestoration}>
{countryList.map(country => (
<li>{country}</li>
))}
</ul>
)
}
对于更全局的方法,您还可以使用 gatsby-browser.js
API,例如 onRouteUpdate
and shouldUpdateScroll
,两者都会在每次页面更改(导航)时触发:
exports.onRouteUpdate = () => {
if (typeof window !== `undefined`) { window.scrollTo(0, 0)}
}
exports.shouldUpdateScroll = args => {
return false;
};
默认情况下,shouldUpdateScroll
获取最后滚动的位置,理想情况下,只需更改并返回 false
它应该适用于您描述的场景。