如何在NextJS的_document.js中获取Cookie以动态切换主题?
要实现通过Cookie动态给body分配className切换主题,你可以在_document.js的服务端逻辑里解析请求头中的Cookie,把主题值传递给组件后动态渲染类名,完整代码如下:
import NextDocument, { Html, Head, Main, NextScript } from 'next/document' // 解析Cookie字符串为键值对对象 const parseCookie = (cookie) => { if (!cookie) return {} return cookie.split(';').reduce((acc, item) => { const [key, value] = item.trim().split('=') acc[key] = value return acc }, {}) } function Document(props) { // 从props获取主题值,默认设为lightMode const theme = props.theme || 'lightMode' return ( <Html lang="en"> <Head /> {/* 动态拼接body的className */} <body className={`bgimg ${theme}`}> <Main /> <NextScript /> </body> </Html> ) } Document.getInitialProps = async (ctx) => { const initialProps = await NextDocument.getInitialProps(ctx) // 从服务端请求头中获取Cookie并解析 const cookies = parseCookie(ctx.req?.headers.cookie) // 提取Cookie中的theme字段,没有则用默认值 const theme = cookies.theme || 'lightMode' return { ...initialProps, theme } } export default Document
关键说明
parseCookie工具函数负责把Cookie字符串转换成便于读取的键值对对象- 服务端渲染时,
ctx.req.headers.cookie能拿到请求携带的所有Cookie,前端浏览器环境下不需要这里的逻辑(因为_document只在服务端执行) - 把解析出的主题值作为props传给Document组件,就能动态生成body的className,实现主题的服务端初始化渲染
内容的提问来源于stack exchange,提问作者Rudra Bhikadiya
相关产品推荐
相关产品推荐

