Next.js 9+ 使用 Styled Components 出现闪烁或未经样式处理的内容 (FOUC)。

3

我已经花了几天时间在这个问题上,从大部分的SA和Reddit寻找解决方案和想法,但都没有成功。

在生产和本地加载时,每次加载都会呈现整个HTML而没有任何样式,然后再注入到DOM中。

目前,这是我的项目关键文件:

_document.js

import { ServerStyleSheet } from "styled-components";
import Document, { Main, NextScript } from "next/document";

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }

  render() {
    return (
      <html lang="en">
      <Head>
        <title>namesjames</title>
        <link rel="icon" href="/favicon.ico" />
        <script src="/static/chrome-fix.js" />
        <link href="/above-the-fold.css" />
      </Head>
        <body>

          <script src="/noflash.js" />
          <Main />
          <NextScript />
          <script> </script>
        </body>
      </html>
    );
  }
}

_app.js

/* eslint-disable class-methods-use-this */
import App from "next/app";
import React from "react";
import { ThemeProvider } from "styled-components";
import { ParallaxProvider } from 'react-scroll-parallax';
import Header from "../components/Header";
import theme from "../theme";
import GlobalStyles from "../GlobalStyles";
import DarkModeToggle from '../components/toggle/toggleMode';
import Footer from '../components/Footer'
import LazyLoad from 'react-lazy-load';
import Router from 'next/router';
import styled from 'styled-components'
// import '../style.css'


const Loaded = styled.div`
  opacity: ${(props) => props.loaded ? "1" : "0"};
`

export default class MyApp extends App {
  state = { isLoading: false, loaded: false }

  componentDidMount() {
    // Logging to prove _app.js only mounts once,
    // but initializing router events here will also accomplishes
    // goal of setting state on route change
    console.log('MOUNT');
    this.setState({loaded: true})



    Router.events.on('routeChangeStart', () => {
      this.setState({ isLoading: true });
      console.log('loading is true, routechangeStart')
    });

    Router.events.on('routeChangeComplete', () => {
      this.setState({ isLoading: false });
      console.log('loading is false, routeChangeComplete')
    });

    Router.events.on('routeChangeError', () => {
      this.setState({ isLoading: false });
      console.log('loading is false, routeChangeError')
    });
  }
  render(): JSX.Element {
    const { isLoading } = this.state;
    const { Component, pageProps, router, loaded } = this.props;
    return (
      <Loaded loaded={this.state.loaded}>
        <ThemeProvider theme={theme}>
          <GlobalStyles />
          <ParallaxProvider>
          <Header />
           {isLoading && 'STRING OR LOADING COMPONENT HERE...'}
          <Component {...pageProps} key={router.route} />
          <LazyLoad offsetVertical={500}>
            <Footer />
          </LazyLoad>
          </ParallaxProvider>
          <DarkModeToggle />
        </ThemeProvider>
      </Loaded>
    );
  }
}

index.js

import { color } from "styled-system";
import { OffWhite } from "../util/tokens";
import Hero from "../components/Hero";
import Banner from  '../components/Banner'
import TitleText from '../components/TitleText'
import HomeTitleCopyScene from '../components/HomeTitleCopyScene'
import TwoCards from '../components/TwoCards'
import LazyLoad from 'react-lazy-load';

function Home(): JSX.Element {
  return (
    <div className="container">
      <Banner />
      <HomeTitleCopyScene />
      <LazyLoad offsetVertical={1000}>
        <TwoCards />
      </LazyLoad>
    </div>
  );
}

export default Home;

正如一些人可能已经看到的那样,我尝试了多种实现方式,现在有点困惑,不确定它可能是什么..

任何帮助都将不胜感激,如果需要,我可以提供更多信息.. 非常感谢

2个回答

2

我找到了两种解决方案:

  1. 在JSX中使用硬编码样式opacity:0,然后在DOM中应用样式时将opacity:1 !important注入到任何显示的组件中。

<section className="cards-block" style={{opacity:0}}>

  1. 虽然这个方法今天早上很有效,但我发现在开发过程中,我错误地从next/head导入了Head并在我的_document.js中使用了它,而没有使用正确的Head来自next/documents
// import Head from "next/head"; --> incorrect
import { ServerStyleSheet } from "styled-components";
import Document, { Head, Main, NextScript } from "next/document"; 

Ergo -> 一个正确渲染和注入的元素,没有FOUC。

希望这能帮助到某个人。


真令人讨厌,我和你使用完全相同的代码,只不过正确导入了头文件,但它不起作用。 - undefined
我也一样 :-( 本以为这也会是解决办法! - undefined

0

我已经找到了我的小型组合项目的解决方法:

只需将以下内联 CSS 包含在自定义 _document.js<head> 中:

{<style dangerouslySetInnerHTML={{__html: `

    html {background: #333}
    body #__next div {visibility: hidden}
    body.loaded #__next div {visibility: visible}

`}}></style>}

在 `_app.js` 中,将 "loaded" 类添加到 body 元素中。
if (process.browser) {
    document.body.classList.add("loaded")
}

我不太确定这是否是一个好的解决方案,任何建议都将不胜感激:


我唯一看到的问题是你会失去SSR的好处。基本上,你需要等待水合才能使页面可见。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接