使用 CSS-in-JS 可实现组件级样式动态管理与主题切换,通过 styled-components 等库结合 props 和 ThemeProvider,使样式与状态联动。1. 安装 styled-components 并创建带 props 的动态样式按钮;2. 定义 lightTheme 与 darkTheme 主题对象;3. 使用 ThemeProvider 包裹应用并注入主题;4. 组件通过 props.theme 访问主题变量;5. 利用 useState 实现主题切换功能。最终构建灵活、可维护的动态 UI 系统。

使用 CSS-in-JS 可以将样式逻辑直接写在 JavaScript 中,实现组件级样式的动态管理和主题切换。这种方式让样式与组件状态、props 和主题上下文紧密联动,提升可维护性和灵活性。
选择合适的 CSS-in-JS 库
常见的库如 styled-components、emotion 和 linaria 都支持动态样式和主题管理。其中 styled-components 因其直观的 API 和对 React 主题的良好支持,被广泛采用。
安装示例:
npm install styled-components通过 props 动态调整样式
可以在定义组件时接收 props,并根据其值动态生成样式。这适用于按钮状态、尺寸变化等场景。
立即学习“前端免费学习笔记(深入)”;
示例:根据 primary 属性切换按钮颜色
background: ${props => props.primary ? 'blue' : 'gray'};
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
`;
使用 ThemeProvider 管理主题
styled-components 提供 来注入主题对象,所有子组件可通过 props.theme 访问主题变量。
定义主题并应用:
import { ThemeProvider } from 'styled-components';const lightTheme = {
bg: '#ffffff',
text: '#000000'
};
const darkTheme = {
bg: '#1a1a1a',
text: '#ffffff'
};
// 根组件中包裹
在组件中使用主题:
const Container = styled.div`background: ${props => props.theme.bg};
color: ${props => props.theme.text};
min-height: 100vh;
padding: 20px;
`;
实现主题切换功能
结合 React 的状态管理(如 useState),可以实现用户点击切换主题的功能。
示例:
function App() {const [theme, setTheme] = useState(darkTheme);
const toggleTheme = () => {
setTheme(theme === darkTheme ? lightTheme : darkTheme);
};
return (
欢迎使用主题系统
);
} 基本上就这些。利用 CSS-in-JS,你可以把样式变成可编程的逻辑,配合主题上下文和组件状态,轻松实现高度动态的 UI 表现。










