【发布时间】:2021-07-30 15:49:12
【问题描述】:
使用next10.2,每次我们将带有哈希的URL推送到路由器时,next都会跳转到锚元素。
import {useRouter} from 'next/router'
router.push('/contact#about-us');
如果我禁用scroll,也会发生这种情况
router.push('/contact#about-us', undefined, { scroll: false });
我想平滑滚动到锚元素,而不是将其委托给 next.js。
import React from 'react'
import {useRouter} from 'next/router'
import PropTypes from "prop-types";
const LinkSmoothScroll = ({href, className, children}) => {
const router = useRouter()
const linkClicked = (e) => {
e.preventDefault();
router
.push(href, undefined, {scroll: false})
.then(() => {
const el = document.getElementById(href);
if ( typeof el !== "undefined" ) {
// Since header element is fixed, and document height is not being
// affected by fixed/absolute elements, we need to consider this
// on the margin to be applied.
const headerHeight = document.getElementById("nav-header")?.scrollHeight || 0;
const scrollTopY = el.top + window.scrollY - headerHeight;
window.scrollTo({
left: el.left,
top: scrollTopY,
behavior: 'smooth'
});
}
});
}
return (
<a href={href} className={className} onClick={linkClicked}>{children}</a>
)
}
LinkSmoothScroll.propTypes = {
href: PropTypes.any,
children: PropTypes.string,
className: PropTypes.string
}
export default LinkSmoothScroll;
我没有找到任何方法来禁用此行为,也没有找到避免它的调整。
【问题讨论】:
-
那是因为#about-us,您将用户定向到ID为
about-us的元素 -
@DedaDev 期望的行为是跳转到
contact页面,但preventDefault在跳转到元素时,手动处理(使用平滑滚动)。跨度> -
你是如何手动处理滚动的?你不能阻止那里的默认行为吗?
-
@juliomalves 你说的
not prevent the default behavior是什么意思?我在preventDefault()之后对元素中的点击事件执行router.push()。一旦我删除router.push()我就没有跳跃效果 -
跳转到锚点的行为并不是 Next.js 特有的,它的发生是因为您在导航路径中添加了一个锚点(在这种情况下,当您调用
router.push()时)。你提到你想手动处理跳转 - 你在哪里做?
标签: javascript reactjs next.js