我正在尝试使用 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 />
中收集您的所有款式组件使用 ServerStyleSheet
由styled-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/