【问题标题】:Why smooth scrolling is not working on NextJs为什么平滑滚动不适用于 NextJs
【发布时间】:2019-04-08 14:10:42
【问题描述】:

我找到了一个可以在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)
      })
  }

  //...

【问题讨论】:

    标签: reactjs scroll next.js


    【解决方案1】:

    我想出了这个解决方案,因为当你在同一个页面中时,你不需要等待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,否则它会加载页面然后移动它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多