如何修复NextJS中的暗模式背景色闪烁? [英] How to fix dark mode background color flicker in NextJS?

查看:0
本文介绍了如何修复NextJS中的暗模式背景色闪烁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的问题是,Next.js无法访问客户端上的localStorage,因此将提供默认情况下具有或不具有class="dark"的HTML。

这意味着当用户重新加载页面时,<html>短暂地没有class="dark",导致在执行某个Java脚本并将class="dark"添加到<html>之前,出现浅背景色闪烁。如果我将class="dark"class="dark"一起发送,则会出现相同的问题,但情况正好相反:在class="dark"<html>中删除之前,浅色模式的用户将体验到深色背景的闪烁。

有没有办法在呈现页面之前执行一些Java脚本?然后,我将能够根据用户的localStorage添加或不添加class="dark"<html>

推荐答案

当然,请将noflash.js文件添加到您的公共目录中,其中包含以下内容

(function () {
    // Change these if you use something different in your hook.
    var storageKey = 'darkMode';
    var classNameDark = 'dark-mode';
    var classNameLight = 'light-mode';

    function setClassOnDocumentBody(darkMode) {
        document.body.classList.add(darkMode ? classNameDark : classNameLight);
        document.body.classList.remove(darkMode ? classNameLight : classNameDark);
    }

    var preferDarkQuery = '(prefers-color-scheme: dark)';
    var mql = window.matchMedia(preferDarkQuery);
    var supportsColorSchemeQuery = mql.media === preferDarkQuery;
    var localStorageTheme = null;
    try {
        localStorageTheme = localStorage.getItem(storageKey);
    } catch (err) {}
    var localStorageExists = localStorageTheme !== null;
    if (localStorageExists) {
        localStorageTheme = JSON.parse(localStorageTheme);
    }

    // Determine the source of truth
    if (localStorageExists) {
        // source of truth from localStorage
        setClassOnDocumentBody(localStorageTheme);
    } else if (supportsColorSchemeQuery) {
        // source of truth from system
        setClassOnDocumentBody(mql.matches);
        localStorage.setItem(storageKey, mql.matches);
    } else {
        // source of truth from document.body
        var isDarkMode = document.body.classList.contains(classNameDark);
        localStorage.setItem(storageKey, JSON.stringify(isDarkMode));
    }
})();

// https://github.com/donavon/use-dark-mode/blob/develop/noflash.js.txt

然后,将以下script src标记添加到pages/_document文件的Head类中包装的返回内容

import Document, {
    Head,
    Html,
    Main,
    NextScript,
    DocumentContext
} from 'next/document';

class MyDocument extends Document {
    static async getInitialProps(ctx: DocumentContext) {
        const initialProps = await Document.getInitialProps(ctx);
        return { ...initialProps };
    }
    render() {
        return (
            <Html lang='en-US'>
                <Head>
                    <meta charSet='utf-8' />
                    <script type="text/javascript" src='/noflash.js' />
                </Head>
                <body className='loading'>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        );
    }
}

export default MyDocument;

上面的方法可以工作,但下面的方法与Nextv10+配合得很好。它只需要将以下配置添加到根next.config.js文件中。

next.config.js

module.exports = {
  env: {
    noflash: fs.readFileSync('/noflash.js').toString()
  }
}

然后,更改pages/_document文件中的以下脚本标记,如下所示

before

//
        <Head>
            <meta charSet='utf-8' />
            <script type="text/javascript" src='/noflash.js' />
        </Head>
//

after

//
        <Head>
            <meta charSet='utf-8' />
            <script type="text/javascript" dangerouslySetInnerHTML={{ __html: process.env.noflash}} />
        </Head>
//

Link to a repo where I use the first approach(从2020年秋季开始,在TailWincss内置暗模式支持之前)

这篇关于如何修复NextJS中的暗模式背景色闪烁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆