gpt4 book ai didi

next.js - 使用 Next.js 如何在 SSR 期间向 body 或 _next div 添加一个类?

转载 作者:行者123 更新时间:2023-12-03 19:18:02 24 4
gpt4 key购买 nike

我有一个用例,我必须在 SSR 期间向根元素添加一个类,它可能是 body 或 _next。该类需要根据 getInitialProps 响应有条件地/动态地添加。
我想知道在 Next.js 的当前状态下这是否可能。

最佳答案

import React from 'react';
import NextDocument, {Html, Head, Main, NextScript} from 'next/document';

class Document extends NextDocument {
static async getInitialProps(ctx) {
const initialProps = await NextDocument.getInitialProps(ctx);

// Determine if class name should be added
return {
...initialProps,
shouldShow: true
};
}

render() {
return (
<Html>
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
{
`#__next {
height: ${this.props.shouldShow ? '100%' : '0'}
}
`}
</style>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}

export default Document;

关于next.js - 使用 Next.js 如何在 SSR 期间向 body 或 _next div 添加一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60088660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com