lar*_*_82 5 javascript reactjs server-side-rendering next.js
我正在尝试styled-components使用 Nextjs 在 React 项目中实现。问题是,虽然我可以实现并看到样式,但是当我在浏览器上看到它时会有一点延迟。首先加载没有样式的组件,22 毫秒后应用样式。我做错了什么?谢谢
这是我的代码!
页面/index.js
import React from "react";
import Home from "../components/home/index";
const index = () => {
return (
<React.Fragment>
<Home />
</React.Fragment>
);
};
export default index;
Run Code Online (Sandbox Code Playgroud)
组件/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;
Run Code Online (Sandbox Code Playgroud)
babel.rc
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}
Run Code Online (Sandbox Code Playgroud)
页面/_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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为您的样式正在客户端应用。您需要根据 Next.js 提供的示例进行此修改。
您实际上需要创建一个自定义 Document<App /> ,使用ServerStyleSheet提供的组件从组件中收集所有样式styled-components并将它们应用到服务器端,因此当您的应用程序到达客户端时,样式已经存在。
正如他们在README这个例子中也指出的那样:
为此,我们扩展 并将
<Document />服务器端渲染样式注入到 中<head>,并添加 babel-plugin-styled-components (这是服务器端渲染所需的)。
我希望这能解决您的问题。
| 归档时间: |
|
| 查看次数: |
2020 次 |
| 最近记录: |