【问题标题】:Link stylesheet with media query to React component将带有媒体查询的样式表链接到 React 组件
【发布时间】:2016-12-30 11:44:00
【问题描述】:

在 html 文件中,可以像这样链接样式表:

    <link rel="stylesheet" media="(min-width: 768px)" href="small.css">
    <link rel="stylesheet" media="(min-width: 1150px)" href="big.css">

在 JSX 文件中,您只能导入 css 文件,例如:import "./big.css"

如何根据屏幕大小有条件地将 CSS 文件导入 React 组件?

【问题讨论】:

  • 答案将取决于您如何构建/捆绑您的应用程序。 React/JSX 本身不支持“导入 css 文件”。
  • 您可以尝试使用 css 模块 - github.com/gajus/react-css-modules ,但条件导入部分将取决于您的捆绑方式。或者,您可以只使用 1 个带有媒体查询的样式表 ...
  • 我正在使用 webpack 并且有一个 css 加载器,它只是捆绑应用程序中的每个 css 文件。然后我像这样访问一个捆绑的 css 文件: import "./example.css"

标签: javascript html css reactjs


【解决方案1】:

您可以在“index.js”或您正在使用的任何基本 js 文件中导入您的查询 css 文件。像这样导入import './style.css' 就足够了。无法将样式表与媒体查询链接以响应组件。

【讨论】:

    【解决方案2】:

    您可以使用 require 和有条件地导入模块,如下例所示:

    if (window.innerWidth < 480) {
      require('./index.css')
    }
    

    如果你更喜欢使用 ES6 import,它不能开箱即用,你需要配置它。查看 babel 插件动态导入here

    Note: the above example works after a reload if you are dynamically changing screen size in browser but, if you initially start with a smaller screen size, the css will load. if you need to dynamically re-render your component when the user or developer resizes the browser window, then implement that logic for re-rendering your component based on screen size

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 2014-03-18
      • 2013-10-19
      • 2020-04-14
      • 1970-01-01
      • 2021-10-26
      • 2019-10-11
      • 1970-01-01
      • 2020-05-21
      相关资源
      最近更新 更多