【问题标题】:Next.js, Styled-components and Yandex Metrica Session ReplayNext.js、Styled-components 和 Yandex Metrica 会话重放
【发布时间】:2021-04-11 09:13:34
【问题描述】:

我正在一个使用 Next.js 和 styled-components 的项目中工作。在我的文件 [slug].tsx:

export default function ProductDetails({ product }: IProductDetailsProps) {
  const router = useRouter();

  if (router.isFallback) {
    return (
      <LoadingContainer>
        <ReactLoading color="#000" type="bubbles" />
      </LoadingContainer>
    );
  }

  return (
    <>
      {product._id ? (
        <>
          <Header />

          <Container>
            <ProductPath>
              <Link href="/">Home</Link>

              <Link href="/shop">Shop</Link>

              {product.categoryId && (
                <Link href={`/shop/${product.categoryId.slug}`}>
                  {product.categoryId.name}
                </Link>
              )}

              <span>{product.name}</span>
            </ProductPath>

            <ProductInfo product={product} />
          </Container>
        </>
      ) : (
        <Error>An unexpected error has occurred.</Error>
      )}
    </>
  );
}

大部分标签来自 styled-components,例如:

export const LoadingContainer = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
`;

export const Error = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
`;

export const Container = styled.div``;

export const ProductPath = styled.p`
  display: block;
  padding: 22px 32px;
  font-size: 14px;
  background-color: #f1f1f1;

  a {
    text-decoration: none;
    color: #09c;

    transition: color 0.2s;

    &:hover {
      color: #fcb800;
    }
  }

  a + a::before,
  a + span::before {
    content: '/';
    color: #000;
    cursor: auto;
    margin: 0 10px;
  }
`;

我关注了 Next.js (https://styled-components.com/docs/advanced#nextjs) 的 styled-components 文档,我的 .babelrc:

{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}

_document.tsx:

import Document, { DocumentContext } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    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();
    }
  }
}

这个项目需要 Yandex Session Replay 工作,但是当我的应用程序在生产中加载时,控制台中没有错误并且 Yandex Session Replay 不呈现 CSS:

session replay not rendering CSS

有什么建议吗?

谢谢。

【问题讨论】:

    标签: typescript next.js styled-components yandex-metrika session-replay


    【解决方案1】:

    尝试像这样在_document 组件中添加渲染函数:

    import Document, {
      Html,
      Head,
      Main,
      NextScript,
      DocumentContext
    } from 'next/document'
    import { ServerStyleSheet } from 'styled-components'
    
    export default class MyDocument extends Document {
      static async getInitialProps(ctx: DocumentContext) {
        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 lang="en">
            <Head />
            <body>
              <Main />
              <NextScript />
            </body>
          </Html>
        )
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      • 2018-04-14
      • 2022-08-06
      • 1970-01-01
      • 2021-01-09
      • 2023-03-24
      • 2021-05-12
      相关资源
      最近更新 更多