javascript - Nextjs 中的样式组件延迟设置属性

标签 javascript reactjs next.js server-side-rendering

我正在尝试使用 Nextjs 在 React 项目中实现 styled-components。问题是,虽然我可以实现并查看样式,但当我在浏览器上看到它时,会有一点延迟。首先它加载没有样式的组件,22 毫秒后应用样式。我做错了什么? 谢谢

这是我的代码!

pages/index.js

import React from "react";
import Home from "../components/home/index";


const index = () => {
  return (
    <React.Fragment>
        <Home />
    </React.Fragment>
  );
};

export default index;

组件/home.js

import React from "react";
import styled from 'styled-components';

const Title = styled.h1`
  color: red;
`;

function Home() {
  return (
    <div>
      <Title>My First Next.js Page</Title>
    </div>
  );
}

export default Home;

babel.rc

{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}

pages/_document.js

import Document from 'next/document';
import { ServerStyleSheet } from 'styled-components';

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();
    }
  }
}

最佳答案

发生这种情况是因为您的样式正在客户端应用。您需要关注this modification来自 Next.js 提供的示例。

您实际上需要创建一个 custom Document ,从您的 <App /> 中收集您的所有款式组件使用 ServerStyleSheetstyled-components提供并将它们应用到服务器端,因此当您的应用程序到达客户端时,样式已经存在。

正如他们在 README 上所说的那样本例的内容:

For this purpose we are extending the <Document /> and injecting the server side rendered styles into the <head>, and also adding the babel-plugin-styled-components (which is required for server side rendering).

我希望这能解决您的问题。

关于javascript - Nextjs 中的样式组件延迟设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59672605/

相关文章:

javascript - React(next.js) 给了我 "handleSubmit is not defined"

javascript - 使用 React-router 和 requirejs 进行 React 的基本设置

javascript - 更改页面而不刷新页面中的 div

reactjs - React Onclick - 没有重载匹配这个调用

ios - 获取 npm 错误!退出,错误代码为 : 128

javascript - Next.JS 代码如何在服务器和客户端上运行?

javascript - 添加 onclick 属性以使用 JavaScript 输入

javascript - 当数据少于 3 个值时,AMCharts 系列不出现的问题

javascript - 如何使用字符串数组作为 react 选择中的选项

reactjs - 如何在nextjs中导航而不会丢失标题组件的状态