dihuaooo 2025-02-26 15:49 采纳率: 0%
浏览 6

next antdesign 刷新页面

next.js 使用 antDesign5 每次刷新页面组件的样式会失效 然后过两秒会才会恢复正常

  • 写回答

2条回答 默认 最新

  • 阿里嘎多学长 2025-02-26 15:49
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    解决方案

    你遇到的问题是 Next.js 使用 Ant Design 5,每次刷新页面组件的样式会失效,然后过两秒才会恢复正常。

    这是因为 Ant Design 5 使用了 CSS-in-JS 机制,Next.js 的 Server-Side Rendering (SSR) 机制会导致样式的失效。

    解决方案:

    1. next.config.js 文件中添加以下配置:
    module.exports = {
      // ...
      experimental: {
        // 使用 Ant Design 5 的 CSS-in-JS 机制
        cssModules: true,
      },
    };
    
    1. 在组件中使用 useEffect Hook来延迟样式的应用:
    import { useState, useEffect } from 'react';
    import { Button } from 'antd';
    
    function MyButton() {
      const [style, setStyle] = useState({});
    
      useEffect(() => {
        // 延迟 2 秒后应用样式
        setTimeout(() => {
          setStyle({ backgroundColor: 'red' });
        }, 2000);
      }, []);
    
      return (
        <Button style={style}>点击我</Button>
      );
    }
    
    1. 或者,你可以使用 getStaticProps 方法来预先生成组件的样式:
    import { Button } from 'antd';
    
    export async function getStaticProps() {
      return {
        props: {
          style: {
            backgroundColor: 'red',
          },
        },
      };
    }
    
    function MyButton() {
      return (
        <Button style={props.style}>点击我</Button>
      );
    }
    

    这些解决方案都可以帮助你解决 Ant Design 5 在 Next.js 中的样式失效问题。

    评论

报告相同问题?

问题事件

  • 创建了问题 2月26日