是否可以在 React 中有条件地加载某个 css 文件

Is is possible to conditionally load a certain css file in React

所以我目前在 React v17.0.2 中有一个前端应用程序 运行,我需要有条件地加载一个 css 文件。我有一个 html 开关可以在暗模式和亮模式之间切换,目前我有这段代码,它在本地主机上完美运行:

function App() {
    const { Content } = Layout;

    const rootStore = useContext(RootStoreContext);
    const { token, appLoading, setAppLoading, lightMode } = rootStore.commonStore;
    const { getUser } = rootStore.userStore;
    
    if (lightMode) { 
        require('antd/dist/antd.css');
    }
    else {
        require('antd/dist/antd.dark.css');
    }

就像我说的那样,代码在 localhost 上运行完美,但是当我将其部署到 azure 并单击开关更改主题时,我收到以下错误:

VM648:3 Uncaught TypeError: Cannot read properties of undefined (reading 'cosmeticStyleSheet')
    at <anonymous>:3:39
    at <anonymous>:26:11

所以我假设我的做法是错误的,正确的做法是什么?

感谢您的指导!

我们重新措词 google 搜索提出了一个类似的问题

在这里回答: conditional css in create-react-app