问题
I have a use case where I have to add a class to a root element may it be body or _next during SSR. The class needs to be added conditionally/dynamically based on getInitialProps responses. I want to know if such is possible in the current state of Next.js.
回答1:
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;
来源:https://stackoverflow.com/questions/60088660/using-next-js-how-to-add-a-class-to-body-or-next-div-during-ssr