如何在Next.js中用styled-components设置Hero区域全屏背景图
解决Next.js中styled-components背景图不显示+类名不匹配问题
一、先搞定「className不匹配」的警告
这个警告是Next.js服务端渲染时,styled-components在服务端和客户端生成的类名不一致导致的,不解决的话样式大概率出问题。按下面步骤配置:
- 安装依赖:
npm install styled-components babel-plugin-styled-components
- 根目录建
.babelrc文件,写入以下内容:
{ "presets": ["next/babel"], "plugins": [["styled-components", { "ssr": true }]] }
- 在
pages文件夹下创建_document.js,代码如下:
import Document, { Html, Head, Main, NextScript } 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() } } render() { return ( <Html> <Head /> <body> <Main /> <NextScript /> </body> </Html> ) } }
二、修复全屏背景图不显示的问题
场景1:图片放在public文件夹里
直接用绝对路径引用,比如public下的hero-bg.jpg,写法如下:
const HeroImage = styled.div` width: 100%; min-height: 100vh; background-image: url('/hero-bg.jpg'); background-repeat: no-repeat; background-size: cover; background-position: center; `
场景2:从项目目录导入图片(比如assets文件夹)
先导入图片,再在styled-components里用它的src属性:
import heroBg from '../assets/hero-bg.jpg'; const HeroImage = styled.div` width: 100%; min-height: 100vh; background-image: url(${heroBg.src}); background-repeat: no-repeat; background-size: cover; background-position: center; `
配置完上面的内容后,重启Next.js开发服务器,类名不匹配的警告会消失,全屏背景图也能正常显示了。
内容的提问来源于stack exchange,提问作者Dan Laratta
相关产品推荐
相关产品推荐

