【问题标题】:React – Import Stylesheet **only if** UserAgent is MobileReact – 导入样式表**仅当** UserAgent 是移动设备时
【发布时间】:2026-01-26 05:25:01
【问题描述】:

希望仅在 UserAgent 是移动设备时导入特定于移动设备的样式表。

集成了这个UserAgent检测包,所以我们可以成功检测到UserAgent:https://www.npmjs.com/package/react-useragent

只是不知道如何导入 mobile.css 仅当 UserAgent 是移动的。谢谢!

/* only load mobile.css if UserAgent is mobile */
import styles from '../../mobile.css';

【问题讨论】:

  • 你在使用 webpack 吗?
  • @MohamedRamrami 是的,我们是。

标签: css reactjs user-agent


【解决方案1】:

条件导入确实存在!它在 Webpack 2 中!这是带有示例和用例的git repo

if (agent === whateverYouWant) {
    import('./mobile.css').then(() => {
       console.log("Imported mobile css");
    });
}

此外,您还可以在条件句中使用require

【讨论】:

    最近更新 更多