react 添加css_在JS中使用情感CSS将暗模式添加到您的React应用中

react 添加css

Dark theme is one of the most requested features over the past few years. The most popular reason is that “it’s easier on the eyes,” followed by “it’s elegant and beautiful.” Apple in their Dark Mode developer documentation explicitly writes: “The choice of whether to enable a light or dark appearance is an aesthetic one for most users, and might not relate to ambient lighting conditions.”

黑暗主题是过去几年中最受欢迎的功能之一。 最受欢迎的原因是“它在眼睛上更容易”,其次是“它优雅而美丽”。 苹果公司在其黑暗模式开发人员文档中明确写道: “对于大多数用户而言,选择启用浅色还是深色外观是一种美感,并且可能与环境照明条件无关。”

Both Apple and Google made a dark theme an essential part of UI, more and more websites do the same to enable dark mode. In this article, I will walk you through some basics of implementing dark mode in a React app.

苹果和谷歌都将深色主题作为UI的重要组成部分, 越来越 多的网站都这样做以启用深色模式。 在本文中,我将向您介绍在React应用程序中实现暗模式的一些基础知识。

设计暗模式 (Designing dark mode)

If you are a developer and working on your project alone, or you don’t have a designer in your team, this section will be useful for you. Otherwise, you could skip this section and jump to the next.

如果您是开发人员并且仅在项目上工作,或者您的团队中没有设计师,那么本部分对您很有用。 否则,您可以跳过此部分,然后跳到下一部分。

As this blog is not a design blog, I will just list some of the basic principles or resources that I found useful.

由于该博客不是设计博客,因此我只列出一些我认为有用的基本原理或资源。

The material design website dark mode page is the best resource I found so far. Here are some of the highlights:

物料设计网站的暗模式页面是我到目前为止找到的最佳资源。 这儿是一些精彩片段:

  • Do not use pure dark #000000 as your background color, it does not look good and create more eye strains than the light mode, use dark grey instead (they use #121212 ).

    不要使用纯深#000000作为背景色,它看起来不佳,并且比明亮模式会产生更多的眼睛疲劳,请改用深灰色(使用#121212 )。

  • In material design, they use Elevation to differentiate the distance between two surfaces along the z-axis (e.g. card, navigation). In light mode, it means darker and wider shadows for higher elevation; in dark mode, it means whiter background.

    在材料设计中,他们使用“ 高程”来区分沿z轴的两个表面之间的距离(例如,卡片,导航)。 在灯光模式下,这意味着阴影更高更暗; 在黑暗模式下,意味着背景更白。

react 添加css_在JS中使用情感CSS将暗模式添加到您的React应用中_第1张图片
Light themes use shadows to express elevation, while a dark theme adjusts the surface color. 浅色主题使用阴影表示高程,而深色主题则调整表面颜色。
  • Dark mode does not mean simply invert all colors, shadow color should still be dark.

    深色模式并不意味着简单地反转所有颜色,阴影颜色仍应为深色。
  • For any elevation or any color-text combination, the contrast ratio should be at least 4.5:1. This means to get 4.5:1 at the highest elevation, you should use a contrast level of at least 15.8:1 between text and the background. (You could use color contrast tools to test contrast ratio.

    对于任何高程或任何颜色文本组合,对比度应至少为4.5:1 。 这意味着要在最高海拔下获得4.5:1,您应该在文本和背景之间使用至少15.8:1的对比度。 (您可以使用颜色对比工具来测试对比度。

  • Use desaturated color to keep the contrast ratio at least 4.5:1. Handling color in dark mode is hard, refer to this article to read more.

    使用不饱和的颜色将对比度保持在至少4.5:1。 在黑暗模式下处理颜色很困难,请参阅本文以了解更多信息。

  • Use light text on dark background and reference table below.

    在深色背景和下面的参考表上使用浅色文字。
react 添加css_在JS中使用情感CSS将暗模式添加到您的React应用中_第2张图片
Text color on dark mode 深色模式下的文字颜色

1.用情感来切换背景和文字 (1. Use emotion to toggle background and text)

Let's start with a simple canvas with text and a button, to change between dark mode and light mode.

让我们从带有文本和按钮的简单画布开始,在暗模式和亮模式之间进行切换。

initial state: white background with dark text 初始状态:带有深色文字的白色背景

At the moment, it does not do anything besides toggling the internal state of isDark value and change text.

目前,除了切换isDark值的内部状态和更改文本外,它什么也不做。

In dark mode, we will want to change:

黑暗模式下,我们将要更改:

  • Text color to #fff

    文字颜色为#fff

  • Background-color to #121212

    背景色为#121212

  • Invert button text, button background-color, and hover colors

    反转按钮文本,按钮背景色和悬停颜色

We are using emotion for styling because it is simple, but the concept will work if you are using pure CSS or CSSModule (you will need to set the theme in context and toggle class name in the component).

我们使用情感进行样式设置是因为它很简单,但是如果您使用纯CSS或CSSModule,则该概念将起作用(您需要在上下文中设置主题并在组件中切换类名称)。

1.1)添加带有主题颜色值的ThemeProvider (1.1) Adding ThemeProvider with the theme color values)

react 添加css_在JS中使用情感CSS将暗模式添加到您的React应用中_第3张图片
index.js index.js

Here we define all the changing colors in an object called themeLight or themeDark and pass it to ThemeProvider. We have refactored the main code to another file called App.js, and we will use the theme values in App.js in next section.

在这里,我们在名为themeLightthemeDark的对象中定义所有变化的颜色,并将其传递给ThemeProvider 。 我们已经将主代码重构为另一个名为App.js文件,我们将在下一部分中使用App.js中的theme值。

1.2)在App.js中使用主题值 (1.2) Using theme values in App.js)

react 添加css_在JS中使用情感CSS将暗模式添加到您的React应用中_第4张图片
App.js App.js

emotion has provided a useful hook useTheme to use a theme in a child component of ThemeProvider. In your style code, you could just change your color with a variable from theme object passed to ThemeProvider. For example:

emotion提供了一个有用的钩子useTheme ,用于在ThemeProvider的子组件中使用主题。 在样式代码中,您可以使用传递给ThemeProvider theme对象中的变量来更改颜色。 例如:

const theme = useTheme();  css={css`
background-color: ${theme.background};
color: ${theme.text};
`}
>

There is another way below to achieve the same goal without useTheme hook, but I feel useTheme could make code a little bit simpler.

下面有另一种无需使用useTheme钩子即可实现相同目标的useTheme ,但我觉得useTheme可以使代码更简单。

  css={theme => css`
background-color: ${theme.background};
color: ${theme.text};
`}
>

1.3)添加动画 (1.3) Adding animations)

Now if you click the button, the theme values will change and the styles will change accordingly. You will notice the changes are too quick and it does not feel natural. If we add some basic CSS transitions, there will be a subtle change in the background and text colors when you press the button.

现在,如果单击该按钮, theme值将更改,样式也将相应更改。 您会发现更改太快,感觉不自然。 如果我们添加一些基本CSS过渡,则当您按下按钮时,背景和文本颜色将发生细微变化。

transition-duration: 0.2s;
transition-property: background-color, color;

The current code looks like this:

当前代码如下:

adding dark mode style with emotion 带有情感的黑暗模式风格

2.根据用户的系统设置设置初始主题 (2. Set the initial theme based on the user’s system settings)

It is nice to toggle by clicking the buttons, but can we do better? If the user is already using dark mode in the system, can we enable dark mode by default instead of asking user to toggle?

单击按钮进行切换很不错,但是我们可以做得更好吗? 如果用户已经在系统中使用了暗模式,是否可以默认启用暗模式,而不是要求用户切换?

There is actually a CSS query for it: prefers-color-scheme

实际上有一个CSS查询: prefers-color-scheme

/* Light mode */
@media (prefers-color-scheme: light) {
html {
background: white;
color: black;
}
}
/* Dark mode */
@media (prefers-color-scheme: dark) {
html {
background: black;
color: white;
}
}

The prefers-color-scheme media feature is used to detect if the user has requested the page to use a light or dark color theme. It works with the following values:

prefers-color-scheme媒体功能用于检测用户是否已请求页面使用浅色或深色主题。 它适用于以下值:

  • no-preference: Indicates that the user has made no preference known to the system. This keyword value evaluates as false in the boolean context.

    no-preference :表示用户没有使系统知道任何偏好。 在布尔上下文中,此关键字值的值为false

  • light: Indicates that the user has notified the system that they prefer a page that has a light theme (dark text on light background).

    light :表示用户已通知系统,他们希望使用具有浅色主题(浅色背景上的深色文本)的页面。

  • dark: Indicates that the user has notified the system that they prefer a page that has a dark theme (light text on dark background).

    dark :指示用户已通知系统,他们希望页面具有深色主题(深色背景上的浅色文本)。

找出浏览器是否支持暗模式 (Finding out if dark mode is supported by the browser)

As dark mode is reported through a media query, you can easily check if the current browser supports dark mode by checking if the media query prefers-color-scheme matches at all.

由于通过媒体查询报告了暗模式,因此您可以通过检查媒体查询是否完全prefers-color-scheme匹配来轻松检查当前浏览器是否支持暗模式。

if (
console.log(' device on Dark mode');
}

At the time of writing, prefers-color-scheme is supported on both desktop and mobile (where available) by Chrome and Edge as of version 76, Firefox as of version 67, and Safari as of version 12.1 on macOS and as of version 13 on iOS. For all other browsers, you can check the Can I Use support tables.

在撰写本文时,Chrome和Edge从76版开始支持桌面和移动设备(如果有),并且在macOS和13版上从版本12.1开始的Firefox和Safari(从版本67开始)都支持prefers-color-scheme在iOS上。 对于所有其他浏览器,您可以检查“ 我可以使用支持表” 。

In our index.js, we just need to change the initial state of useState from false to window.matchMedia('(prefers-color-scheme: dark)').matches

在我们的index.js ,我们只需useState的初始状态从false更改为window.matchMedia('(prefers-color-scheme: dark)').matches useState window.matchMedia('(prefers-color-scheme: dark)').matches

const [isDark, setIsDark] = useDarkMode(
window.matchMedia('(prefers-color-scheme: dark)').matches
);
The App loads dark mode by default 该应用默认加载黑暗模式

结论 (Conclusion)

There are so much more you could go beyond this point: save user preference on a server or local storage, adding dark mode for some complex components like react-select (just grab this gist if you want to get some reference). I have also recently added dark mode to hacker tab chrome extension, you could check the whole commit here.

到目前为止,您还有更多的选择:将用户首选项保存在服务器或本地存储上,为某些复杂的组件(如react-select)添加暗模式(如果您想获得一些参考,请抓住这个要点 )。 我最近还为黑客选项卡chrome扩展程序添加了暗模式,您可以在此处检查整个提交。

另请阅读 (Also Read)

翻译自: https://levelup.gitconnected.com/adding-dark-mode-to-your-react-app-with-emotion-css-in-js-fc5c0f926838

react 添加css

你可能感兴趣的:(react,java,vue,js,设计模式,ViewUI)