我发现了一个可以在next.js
上进行平滑滚动工作的脚本。
这是回购:https://gist.github.com/vinaypuppal/b7271ad84a0d69c9cfafaaa83afed199
我添加了所有必需的内容,并添加了第一条评论建议的更改。但仍然和使用react/link
一样。
问题是它甚至没有调用这段代码:
//#LinkSmoothScroll.js
//...
linkClicked(e) {
e.preventDefault()
Router
.push(this.props.href)
.then(() => {
console.log('test') //this one is not being called at all when I click the <LinkSmoothScroll>
return smoothScroll(this.props.href)
})
.then(() => {
this.props.done && this.props.done()
})
.catch(err => {
this.props.onError && this.props.onError(err)
console.error(err)
})
}
//...
我提出了这个解决方案,因为当你在同一页面时,你不需要等待Router.push()
被执行然后继续使用smoothScrool()
,因为它永远不会。
linkClicked(e) {
e.preventDefault();
const scrollX = window.pageXOffset;
const scrollY = window.pageYOffset;
const location = window.location;
const href = this.props.href;
if (location.pathname === href.split('#')[0]) {
Router.push(this.props.href);
window.scrollTo(scrollX, scrollY);
return smoothScroll(this.props.href)
}
else {
Router
.push(this.props.href)
.then(() => {
window.scrollTo(scrollX, scrollY);
return smoothScroll(this.props.href)
})
.then(() => {
this.props.done && this.props.done()
})
.catch(err => {
this.props.onError && this.props.onError(err)
console.error(err)
})
}
}
因此,如果您位于同一位置,它将只移动到该ID,否则它将加载页面然后移动它。