Izveidosim iespēju React lietotnē pārslēgt tēmas no gaišas uz tumšu…
React Context ļauj definēt globālo stāvokli (global state), nelaižot cauri katram komponentam atsevišķus props. Viens no visizplatītākajiem konteksta lietošanas gadījumiem ir lietojumprogrammas motīva definēšana. Šajā rakstā centīšos Jums parādīt vienu no iespējām, kuru izmantojot Jūs izveidosiet gaišas un tumšas tēmas pārslēdzēju.
Sākuma kodā ir iekļauti visi nepieciešamie lietotāja interfeisa elementi, kā arī komponents Switch, lai pārslēgtu motīvu. Mūsu mērķis ir ieviest trūkstošo funkcionalitāti iekš ThemeContext.js. ThemeContext jau eksportē ThemeProvider komponentu un useTheme āķi. Šobrīd viņi neko nedara un atdod fiktīvas vērtības.
Lai pabeigtu šo uzdevumu, failā ThemeContext.js ir jāievieš gan komponents ThemeProvider, gan āķis useTheme.
ThemeProvider vajadzētu atveidot konteksta nodrošinātāja komponentu un kā konteksta vērtību ievadīt objektu ar diviem rekvizītiem: motīva rekvizītu, kas ir virkne, kas var būt gaiša vai tumša, un funkciju ar nosaukumu toggleTheme, kas ļauj pārslēgt motīvu. Āķim useTheme ir jāatgriež šis konteksta objekts.
1. darbība
Lai izveidotu ThemeProvider, vispirms ir jāizveido jauns konteksta objekts ThemeContext, izmantojot funkciju CreateContext, ko var importēt no React. Noklusējuma vērtības arguments tiek izmantots tikai tad, ja komponentam kokā virs tā nav atbilstoša nodrošinātāja. Šī noklusējuma vērtība var būt noderīga, lai pārbaudītu komponentus atsevišķi, tos neaptinot. Šī uzdevuma vajadzībām tas nav būtisks, tāpēc var izmantot undefined.
Pēc tam komponentā ThemeProvider jums ir jādefinē jauns motīva lokālais statuss, kas var būt virkne, kuras vērtība ir “gaiša” vai “tumša”. To var inicializēt uz “light”, kas parasti ir lietojumprogrammu noklusējuma motīvs.
Return priekšrakstā ir jāatveido komponents ThemeContext.Provider un jāietver bērni.
Visbeidzot, atcerieties, ka ThemeContext.Provider vērtība tiek ievadīta kokā kā konteksts. Tā kā lietojumprogrammai ir nepieciešama gan tēmas vērtība, gan veids, kā to pārslēgt, tiek ievadītas divas vērtības: theme un toggleTheme.
theme ir tikai gaismas-tumšā motīva virknes vērtība, savukārt toggleTheme ir funkcija, kas nesaņem nekādus parametrus un tikai pārslēdz motīvu no gaišas uz tumšu un otrādi.
Tas pabeidz ThemeProvider komponenta ieviešanu, kā norādīts tālāk norādītajā kodā:
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext(undefined);
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider
value={{
theme,
toggleTheme: () => setTheme(theme === "light" ? "dark" : "light"),
}}
>
{children}
</ThemeContext.Provider>
);
};
2. darbība
UseTheme ieviešana ir diezgan vienkārša. Jums vienkārši jāimportē useContext āķis no React un kā arguments jānodod iepriekš definētais ThemeContext objekts. Tas ļauj jūsu komponentiem piekļūt gan motīva, gan toggleTheme vērtībām, kuras atgriež useTheme pielāgotais āķis.
export const useTheme = () => useContext(ThemeContext);
3. darbība
Komponentu Switch pēc tam var savienot ar funkciju toggleTheme, kas atgriezta no useTheme, kā norādīts tālāk norādītajā kodā:
const Switch = () => {
const { theme, toggleTheme } = useTheme();
return (
<label className="switch">
<input
type="checkbox"
checked={theme === "light"}
onChange={toggleTheme}
/>
<span className="slider round" />
</label>
);
};
4. darbība
Visbeidzot, jums vajadzētu būt iespējai izmantot slēdža logrīku augšējā labajā stūrī, lai mainītu lietojumprogrammas motīvu:
Tātad pašam kodam šajos failos vajadzētu vūt šādam:
App.js:
import "./App.css";
import { ThemeProvider, useTheme } from "./ThemeContext";
import Switch from "./Switch";
const Title = ({ children }) => {
const { theme } = useTheme();
return (
<h2
style={{
color: theme === "light" ? "black" : "white",
}}
>
{children}
</h2>
);
};
const Paragraph = ({ children }) => {
const { theme } = useTheme();
return (
<p
style={{
color: theme === "light" ? "black" : "white",
}}
>
{children}
</p>
);
};
const Content = () => {
return (
<div>
<Paragraph>
Pica no itāļu: pizza — 'pīrāgs' ir cepeškrāsnī cepts ar tomātu mērci, sieru un citām piedevām klāts mīklas plācenis.
No neapoliešu virtuves šis ēdiens ir kļuvis populārs daudz kur pasaulē. Veikalus vai restorānus, kas galvenokārt gatavo un pārdod picas, sauc par picērijām.
</Paragraph>
</div>
);
};
const Header = () => {
return (
<header>
<Title>Uzēdam picu? </Title>
<Switch />
</header>
);
};
const Page = () => {
return (
<div className="Page">
<Title>Kad runa ir par picu...</Title>
<Content />
</div>
);
};
function App() {
const { theme } = useTheme();
return (
<div
className="App"
style={{
backgroundColor: theme === "light" ? "white" : "black",
}}
>
<Header />
<Page />
</div>
);
}
function Root() {
return (
<ThemeProvider>
<App />
</ThemeProvider>
);
}
export default Root;
import "./Styles.css";
import { useTheme } from "../ThemeContext";
const Switch = () => {
const { theme, toggleTheme } = useTheme();
return (
<label className="switch">
<input
type="checkbox"
checked={theme === "light"}
onChange={toggleTheme}
/>
<span className="slider round" />
</label>
);
};
export default Switch;
Switch/Styles.css:
.switch {
position: absolute;
display: inline-block;
right: 32px;
width: 60px;
height: 34px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
ThemeContext.js:
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext(undefined);
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider
value={{
theme,
toggleTheme: () => setTheme(theme === "light" ? "dark" : "light"),
}}
>
{children}
</ThemeContext.Provider>
);
};
export const useTheme = () => useContext(ThemeContext);
Atbildēt
Lai komentētu, jums jāpiesakās sistēmā.