当前位置:首页 > React

react实现主题切换

2026-01-26 21:32:36React

实现 React 主题切换的常见方法

使用 CSS 变量和状态管理

通过 React 的状态管理(如 useState 或 Context API)结合 CSS 变量实现主题切换。CSS 变量可以在根元素(:root)中定义,通过 JavaScript 动态修改。

import React, { useState } from 'react';

function App() {
  const [theme, setTheme] = useState('light');

  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    document.documentElement.setAttribute('data-theme', newTheme);
  };

  return (
    <div className="app">
      <button onClick={toggleTheme}>Toggle Theme</button>
      <h1>Current Theme: {theme}</h1>
    </div>
  );
}

export default App;

在 CSS 中定义主题变量:

:root {
  --primary-color: #ffffff;
  --secondary-color: #000000;
}

[data-theme="dark"] {
  --primary-color: #000000;
  --secondary-color: #ffffff;
}

body {
  background-color: var(--primary-color);
  color: var(--secondary-color);
}

使用 Context API 管理主题状态

对于复杂应用,可以通过 Context API 全局管理主题状态,避免 props 层层传递。

react实现主题切换

import React, { createContext, useContext, useState } from 'react';

const ThemeContext = createContext();

export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState('light');

  const toggleTheme = () => {
    setTheme(prevTheme => (prevTheme === 'light' ? 'dark' : 'light'));
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};

export const useTheme = () => useContext(ThemeContext);

在组件中使用:

function ThemedButton() {
  const { theme, toggleTheme } = useTheme();
  return (
    <button onClick={toggleTheme}>
      Current Theme: {theme}
    </button>
  );
}

使用第三方库(如 styled-components)

styled-components 支持主题切换功能,通过 ThemeProvider 传递主题对象。

react实现主题切换

import styled, { ThemeProvider } from 'styled-components';

const lightTheme = {
  background: '#ffffff',
  text: '#000000',
};

const darkTheme = {
  background: '#000000',
  text: '#ffffff',
};

const StyledApp = styled.div`
  background: ${props => props.theme.background};
  color: ${props => props.theme.text};
`;

function App() {
  const [theme, setTheme] = useState(lightTheme);

  const toggleTheme = () => {
    setTheme(theme === lightTheme ? darkTheme : lightTheme);
  };

  return (
    <ThemeProvider theme={theme}>
      <StyledApp>
        <button onClick={toggleTheme}>Toggle Theme</button>
      </StyledApp>
    </ThemeProvider>
  );
}

动态加载主题样式文件

通过动态加载不同的 CSS 文件实现主题切换,适合主题样式较复杂的场景。

function loadTheme(themeName) {
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = `${themeName}.css`;
  document.head.appendChild(link);
}

function App() {
  const [theme, setTheme] = useState('light');

  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    loadTheme(newTheme);
  };

  return (
    <div>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
}

结合 localStorage 持久化主题

将用户选择的主题保存到 localStorage,实现刷新后主题不丢失。

function App() {
  const [theme, setTheme] = useState(
    localStorage.getItem('theme') || 'light'
  );

  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
    document.documentElement.setAttribute('data-theme', newTheme);
  };

  return (
    <div>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
}

注意事项

  • 性能优化:避免频繁的主题切换导致重渲染,尤其是大型应用。
  • 默认主题:在 useEffect 中初始化主题,确保与 localStorage 同步。
  • 无障碍性:确保主题切换不影响屏幕阅读器等辅助工具的使用。

以上方法可根据项目需求灵活选择或组合使用。

标签: 主题react
分享给朋友:

相关文章

react中monent如何获取日期

react中monent如何获取日期

使用 Moment.js 获取当前日期 在 React 中通过 Moment.js 获取当前日期,可以直接调用 moment() 函数。它会返回包含当前日期和时间的 Moment 对象。 impor…

react如何收录

react如何收录

React 收录方法 React 的收录主要涉及搜索引擎优化(SEO)和预渲染技术。由于 React 是单页应用(SPA),默认情况下内容由 JavaScript 动态生成,可能导致搜索引擎爬虫难以收…

react如何浮动

react如何浮动

使用 CSS 实现浮动 在 React 中实现浮动效果可以通过 CSS 的 float 属性完成。在组件的样式文件或内联样式中直接设置 float: left 或 float: right。…

如何安装react

如何安装react

安装React的方法 方法一:使用Create React App(官方推荐) Create React App是官方提供的脚手架工具,适合快速搭建React项目。确保已安装Node.js(建议版本≥…

如何提高react

如何提高react

优化性能 使用React.memo对组件进行记忆化处理,避免不必要的重新渲染。对于类组件,可以使用PureComponent来达到类似效果。 利用useMemo缓存计算结果,避免重复计算。对于函数或…

react如何检测

react如何检测

检测 React 应用的方法 使用 PropTypes 进行类型检查 PropTypes 是 React 内置的类型检查工具,用于验证组件的 props 是否符合预期。在开发环境中,PropTypes…