简体   繁体   English

使用反应挂钩 typescript 设置暗模式

[英]set dark mode using react hooks typescript

React beginner here, english is not my mother language sory for mistakes, i have been looking for setting dark mode on my website, examples what i have seen are mostly toggle between dark and light and you need to specify each colors inside those two.在这里反应初学者,英语不是我的母语对不起,我一直在寻找在我的网站上设置暗模式,我看到的例子大多是在暗和亮之间切换,你需要在这两个中指定每个 colors。 My point is how can i toggle between dark and light(this light should be my default colors set in css)我的观点是如何在黑暗和光明之间切换(这个灯应该是我在 css 中设置的默认 colors)

In my components each has its own css(own colors).If i want to have dark mode which toggles between dark and default css, for example changing background color, how would it be?在我的组件中,每个组件都有自己的 css(自己的颜色)。如果我想要在深色和默认 css 之间切换的深色模式,例如更改背景颜色,会怎样?

my code:我的代码:

 import React, {useState, useEffect } from "react"; ... <div className="app"> <Switch> <Route path="/a"> <A /> </Route> <Route path="/c"> <C /> </Route> <Route path="/b"> <B /> </Route> <Route path="/"> <Redirect to="/a" /> </Route> </Switch> </div>

if need more information, i can give.如果需要更多信息,我可以提供。

You can use a context provider to globally use and update the darkMode state and the local storage to make it persistent on each session.您可以使用上下文提供程序全局使用和更新darkMode state 和本地存储,以使其在每个 session 上持久化。 Make sure to parse your data before setting a item into the local storage.确保在将项目设置到本地存储之前解析您的数据。

Here is a live demo 这是一个现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM