最近在阅读React新版官网的代码时,发现在_app.tsx中有这样一段代码。

  useEffect(() => {
    // Taken from StackOverflow. Trying to detect both Safari desktop and mobile.
    const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
    if (isSafari) {
      // This is kind of a lie.
      // We still rely on the manual Next.js scrollRestoration logic.
      // However, we *also* don't want Safari grey screen during the back swipe gesture.
      // Seems like it doesn't hurt to enable auto restore *and* Next.js logic at the same time.
      history.scrollRestoration = 'auto';
    } else {
      // For other browsers, let Next.js set scrollRestoration to 'manual'.
      // It seems to work better for Chrome and Firefox which don't animate the back swipe.
    }
  }, []);

这里用到了我没有接触过的一个属性History.scrollRestoration,发现这个属性是用来控制页面刷新或者返回后是否滚动到原来的位置。
MDN文档

属性的值:

  1. auto 将恢复用户已滚动到的页面上的位置。
  2. manual 未还原页上的位置。用户必须手动滚动到该位置。

在mdn文档中没有看到auto是默认值,但是自己手动验证以及在在google blog 中提到:

The good news is, however, that there’s a potential fix: history.scrollRestoration. It takes two string values: auto, which keeps everything as it is today (and is its default value), and manual, which means that you as the developer will take ownership of any scroll changes that may be required when a user traverses the app’s history.

所以auto确实是默认值没错。

举例

  1. 如果history.scrollRestoration = ‘auto’;
  2. 如果history.scrollRestoration = ‘manual’;

在react.org/beta(新版官网)中为什么要使用manul

这是因为这个项目用的next.js,涉及到ssr,可能出现页面还没渲染完就滚动到了之前的位置。(待补充例子。)
可以看一下这篇文档Next.js 中怎么保持页面的滚动位置

原文地址:http://www.cnblogs.com/KazooTTT/p/16930302.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性