簡體   English   中英

React 樣式組件中的多個主題

[英]Multiple themes in React styled-components

我使用 React 和 styled-components 庫來為應用程序提供明暗主題。 它工作正常,但我需要添加一個獨立於配色方案的字體系列選擇。 但是如何結合兩個主題(第一個用於配色方案,第二個用於字體)並更改它們?

這是我更改明暗主題的代碼:

import { useEffect, useState } from 'react';

export const useDarkMode = () => {
  const [theme, setTheme] = useState('light');
  const [componentMounted, setComponentMounted] = useState(false);
  const setMode = mode => {
    window.localStorage.setItem('theme', mode)
    setTheme(mode)
  };

  const toggleTheme = () => {
    if (theme === 'light') {
      setMode('dark')
    } else {
      setMode('light')
    }
  };

  useEffect(() => {
    const localTheme = window.localStorage.getItem('theme');
    window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches && !localTheme ?
      setMode('dark') :
      localTheme ?
        setTheme(localTheme) :
        setMode('light');
    setComponentMounted(true);
  }, []);

  return [theme, toggleTheme, componentMounted]
};

這是我的 App.jsx:

import React from 'react';
import { Switch, Route, withRouter } from 'react-router-dom';
import { ThemeProvider } from 'styled-components';
import { GlobalStyles } from '../global';
import { lightTheme, darkTheme } from '../theme';
import { useDarkMode } from '../useDarkMode';

import { Home } from '../../pages';

const App = (props) => {

  const [ theme, toggleTheme ] = useDarkMode();
  const themeMode = theme === 'light' ? lightTheme : darkTheme;

  return (
    <ThemeProvider theme={themeMode}>
      <div>
        <GlobalStyles />  
        <Switch>
          <Route exact path='/' component={Home}></Route>
        </Switch>
      </div>
    </ThemeProvider>
  )
}

export default withRouter(App);

您可以通過更新主題本身來使用您想要的字體樣式更新主題:

 import { useEffect, useState } from 'react'; export const useDarkMode = () => { const [theme, setTheme] = useState('light'); /*... */ const toggleFontStyle = () => { // To toggle between two font styles, or you can pass style as a parameter if (theme.fontStyle === 'SomeStyle') { setTheme({...theme, fontStyle: 'OtherStyle' }) } else { setTheme({...theme, fontStyle: 'SomeStyle' }) } } /*.... */ return [theme, toggleTheme, toggleFontStyle, componentMounted] };

讓我知道是否有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM