Reactjs 可以在styled component@media query中使用Sass变量吗?

Reactjs 可以在styled component@media query中使用Sass变量吗?,reactjs,sass,styled-components,Reactjs,Sass,Styled Components,我已经定义了sass变量$mobile $mobile: "(min-width: 320px) and (max-width:479px)"; 因此,在scss文件中需要使用@media查询的每个地方,我都可以按以下方式使用它: @media #{$mobile} { max-width: 100%; width: 100%; height: 100%; } 是否可以以相同的方式使用$mobile变量 我已尝试像导出其他sa

我已经定义了sass变量
$mobile

$mobile: "(min-width: 320px) and (max-width:479px)";
因此,在
scss
文件中需要使用
@media
查询的每个地方,我都可以按以下方式使用它:

@media #{$mobile}  {
      max-width: 100%;
      width: 100%;
      height: 100%;
    }
是否可以以相同的方式使用
$mobile
变量

我已尝试像导出其他sass变量一样导出此变量:

:root {
  --c-global-red: #{$c-global-red};
  --mobile: #{$mobile};
}
现在,如果我需要在样式化组件中使用例如
$c-global-red
,我可以按如下操作:

const StyledDiv = styled.div`
    color: var(--c-global-red);
`
我可以使用相同的方法将
--mobile
变量与
@media
标记一起使用吗? 大概是这样的:

const StyledDiv = styled.div`
    color: var(--c-global-red);
    @media var(--mobile) {
        color: blue;
    }
`

虽然可以在样式化组件中引用全局CSS变量,但不能引用sass变量或包含字符串的全局CSS变量。相反,您需要利用主题变量


演示 在Codesandbox编辑器中,左右移动中间滚动条,以查看
按钮中的更改

之所以这样做是因为创建样式时,
theme.mobile
被插入到
(最小宽度:320px)和(最大宽度:479px)

@媒体(最小宽度:320px)和(最大宽度:479px){…}
然而,
var(--example)
只是插入字符串
“var(--example)”
,这是无效的:

@media var(--mobile){…}
注意,这可能被认为是反模式的,因为您依赖于全局CSS样式表中的全局CSS变量。您可以通过使用完全避免使用CSS


代码 App.js

import { ThemeProvider, css } from "styled-components";
import Button from "./Button";
import "./styles.css";

const theme = {
  mobile: "(min-width: 320px) and (max-width:479px)"
};

export default function App() {
  return (
    <div className="app">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Button>No Theme</Button>
      <br />
      <ThemeProvider theme={theme}>
        <Button>With Theme</Button>
      </ThemeProvider>
    </div>
  );
}
样式。css

import { ThemeProvider, css } from "styled-components";
import Button from "./Button";
import "./styles.css";

const theme = {
  mobile: "(min-width: 320px) and (max-width:479px)"
};

export default function App() {
  return (
    <div className="app">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Button>No Theme</Button>
      <br />
      <ThemeProvider theme={theme}>
        <Button>With Theme</Button>
      </ThemeProvider>
    </div>
  );
}
.app{
字体系列:无衬线;
文本对齐:居中;
}
身体{
保证金:0;
填充:0;
}
:根{
--蓝色:#1e87f0;
--暗蓝色:#0f7ae5;
--白色:#ffffff;
--粉红色:#ff93ac;
--暗链接:#ff6289;
}