虽然您可以在样式组件中引用全局 CSS 变量,但您不能引用 sass 变量或包含字符串的全局 CSS 变量。相反,您需要将 ThemeProvider 与主题变量结合使用。
演示
在 Codesandbox 编辑器中,通过左右移动来调整中间滚动条以查看 Button 的变化。
之所以有效是因为theme.mobile 在创建样式时被插入到"(min-width: 320px) and (max-width:479px)":
@media (min-width: 320px) and (max-width:479px) { ... }
而var(--example) 只是插入到字符串"var(--example)" 中,这是无效的CSS syntax:
@media var(--mobile) { ... }
请注意,这可能会或可能会被视为反模式,因为您依赖于全局 CSS 样式表中的全局 CSS 变量。您可以完全避免使用 CSS,只需使用 theme variables。
代码
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>
);
}
Button.js
import styled from "styled-components";
const Button = styled.button`
cursor: pointer;
color: var(--white);
background: var(--blue);
outline: 0;
border: 0;
margin: 10px 0;
border-radius: 3px;
padding: 20px;
:hover {
background: var(--darkblue);
}
${({ theme }) =>
`@media ${theme.mobile} {
${css`
background: var(--pink);
:hover {
background: var(--darkpink);
}
`}
}`}
`;
export default Button;
styles.css
.app {
font-family: sans-serif;
text-align: center;
}
body {
margin: 0;
padding: 0;
}
:root {
--blue: #1e87f0;
--darkblue: #0f7ae5;
--white: #ffffff;
--pink: #ff93ac;
--darkpink: #ff6289;
}