Käyttöliittymäteeman vaihtaminen (tumma tila) React and Recoilin avulla

Käyttöliittymäteeman vaihtaminen (tumma tila) React and Recoilin avulla

Lähdesolmu: 1781487

HUOMAA: Tämä opetusohjelma koskee kehittäjiä, jotka käyttävät CSS-in-JS-tyyliä, esim. Emotion.js, Material UI jne.

Vaihe 1: Käytä Recoil atomia valitun teeman nimenä

import { PaletteMode } from "@mui/material";
import { atom } from "recoil"; export const ThemeName = atom<PaletteMode>({ key: "ThemeName", effects: []
});

Vaihe 2: Käytä Recoil-valitsinta tällä hetkellä valitulle teemaobjektille

import { createTheme } from "@mui/material";
import { selector } from "recoil"; export const Theme = selector({ key: "Theme", dangerouslyAllowMutability: true, get(ctx) { const name = ctx.get(ThemeName); return createTheme(); },
});

Vaihe 3: Lisää useTheme(), useToggleTheme() Reagoi koukut

import { useRecoilValue, useRecoilCallback } from "recoil"; export function useTheme() { return useRecoilValue(Theme);
} export function useToggleTheme() { return useRecoilCallback( (ctx) => () => { ctx.set(ThemeName, (prev) => (prev === "dark" ? "light" : "dark")); }, [] );
}

Vaihe 4: Tallenna/palauta valitun teeman nimi kohteeseen/ mistä localStorage

export const ThemeName = atom<PaletteMode>({ key: "ThemeName", effects: [ (ctx) => { const storageKey = "theme"; if (ctx.trigger === "get") { const name: PaletteMode = localStorage?.getItem(storageKey) === "dark" ? "dark" : localStorage?.getItem(storageKey) === "light" ? "light" : matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light"; ctx.setSelf(name); } ctx.onSet((value) => { localStorage?.setItem(storageKey, value); }); }, ],
});

Vaihe 5: Lisää ThemeProvider ylimmän tason React-komponenttiin

import { ThemeProvider } from "@mui/material";
import { useTheme } from "../theme/index.js"; function App(): JSX.Element { const theme = useTheme(); return ( <ThemeProvider theme={theme}> {/* ... */} </Theme> );
}

nähdä app/theme/index.ts in React Starter Kit

Esittelymateriaalit

Aikaleima:

Lisää aiheesta Codementor React Fact