react css多个变量

CSS variables are really cool. You can use them for a lot of things, like applying themes in your application with ease.

CSS变量真的很棒。 您可以将它们用于很多事情,例如轻松地在应用程序中应用主题。

In this tutorial I'll show you how to integrate them with React to create a ThemeComponent (with context!).

在本教程中,我将向您展示如何将它们与React集成以创建ThemeComponent (带有上下文!)。

要点中CSS变量 (CSS Variables in a Gist)

So first of all, I'd like to explain briefly what CSS variables (or in their formal name - CSS custom properties) are, and how to use them.

因此,首先,我想简单地解释一下什么是CSS变量(或以它们的正式名称-CSS自定义属性)以及如何使用它们。

CSS variables are a way for us to define variables that will be applied throughout our application. The syntax is as follows:

CSS变量是我们定义将在整个应用程序中应用的变量的一种方式。 语法如下:

What happens here? Using the --{varName} notation we can tell our browser to store a unique variable called varName (or in the example above, primary), and then we can use it with the var(--{varName}) notation anywhere in our .css files.

发生什么事了? 使用--{varName}表示法,我们可以告诉我们的浏览器存储一个称为varName的唯一变量(或者在上面的示例中,是primary ),然后可以将其与var(--{varName})表示法一起使用。 .css文件。

Does it seem really simple? That's because it is. There's not much to it. According to caniuse.com over 92% of users world wide use a browser that supports CSS variables (unless you really need IE support, in which case you're out of luck). So for the most part they're completely safe to use.

看起来真的很简单吗? 那是因为。 没什么。 根据caniuse.com的说法, 全世界有超过92%的用户使用支持CSS变量的浏览器(除非您确实需要IE支持,否则就不走运了)。 因此,在大多数情况下,它们是完全安全的。

If you want to read more, you can find more information in the MDN page.

如果您想了解更多信息,可以在MDN页面上找到更多信息。

从JavaScript设置CSS变量 (Setting CSS Variables from JavaScript)

Setting and using CSS variables from JavaScript is just as easy as setting and using them in CSS. To get a value defined on an element:

从JavaScript设置和使用CSS变量就像在CSS中设置和使用变量一样容易。 要获取在元素上定义的值:

const primary = getComputedStyle(element).getPropertyValue("--primary");

Will give us the value of the primary custom CSS property defined for the element.

将为我们提供为element定义的primary自定义CSS属性的值。

Setting a custom CSS property works like so:

设置自定义CSS属性的方式如下:

element.style.setProperty("--light", "#5cd2b6");

Or, if we want to set the property for the entire application, we can do:

或者,如果我们要为整个应用程序设置属性,则可以执行以下操作:

document.documentElement.style.setProperty("--light", "#5cd2b6");

And now the light property will be accessible to all of our code.

现在,我们所有的代码都可以访问light属性。

实质性React上下文 (React Context in a Gist)

The React Context API is the only way provided by React to pass props indirectly from one component to a descendent component.

React Context API是React提供的唯一将prop从一个组件间接传递给后代组件的方法。

In this guide I'll use the useContext hook, which you can read more about here. But the principle is the same with class components.

在本指南中,我将使用useContext挂钩,您可以在这里信息。 但是原理与类组件相同。

First, we must initialize a context object:

首先,我们必须初始化一个上下文对象:

import React from "react";export const ThemeSelectorContext = React.createContext({themeName: "dark"
});

The parameters passed to the React.createContext function are the default parameters of the context. Now that we have a context object, we can use it to "inject" props to our indirect descendants:

传递给React.createContext函数的参数是上下文的默认参数。 现在我们有了一个上下文对象,我们可以使用它来将道具“注入”到我们的间接后代中:

export default ({ children }) => (<ThemeSelectorContext.Provider value={{ themeName: "dark" }}>{children}</ThemeSelectorContext.Provider>
);

And now anyone who wants to read the values in our context can do it:

现在,任何想要在我们的上下文中读取值的人都可以做到:

import React, { useContext } from "react";import { ThemeSelectorContext } from "./themer";export default () => {const { themeName } = useContext(ThemeSelectorContext);return <div>My theme is {themeName}</div>;
};

A Voilà! No matter where in the component hierarchy our component lies, it has access to the themeName variable. If we want to allow editing the value in our context, we can pass a function like so:

一个Voilà! 无论我们的组件位于组件层次结构中的哪个位置,它都可以访问themeName变量。 如果要允许在上下文中编辑值,则可以传递如下函数:

export default ({ children }) => {const [themeName, setThemeName] = useState("dark");const toggleTheme = () => {themeName === "dark" ? setThemeName("light") : setThemeName("dark");};return (<ThemeSelectorContext.Provider value={{ themeName, toggleTheme }}>{children}</ThemeSelectorContext.Provider>);
};

And to use it:

并使用它:

import React, { useContext } from "react";import { ThemeSelectorContext } from "./themer";export default () => {const { themeName, toggleTheme } = useContext(ThemeSelectorContext);return (<><div>My theme is {themeName}</div><button onClick={toggleTheme}>Change Theme!</button></>);
};

That's enough for our needs, but if you want you can further read on the Official React Context Documentation.

这足以满足我们的需求,但是如果您愿意,可以进一步阅读Official React Context Documentation 。

放在一起 (Putting Everything Together)

Now that we know how to set CSS custom properties from JavaScript, and we can pass props down our component tree, we can make a really nice and simple "theme engine" for our application. First up we'll define our themes:

现在,我们知道如何从JavaScript设置CSS自定义属性,并且可以将props传递到组件树下,我们可以为应用程序创建一个非常漂亮且简单的“主题引擎”。 首先,我们将定义主题:

const themes = {dark: {primary: "#1ca086",separatorColor: "rgba(255,255,255,0.20)",textColor: "white",backgroundColor: "#121212",headerBackgroundColor: "rgba(255,255,255,0.05)",blockquoteColor: "rgba(255,255,255,0.20)",icon: "white"},light: {primary: "#1ca086",separatorColor: "rgba(0,0,0,0.08)",textColor: "black",backgroundColor: "white",headerBackgroundColor: "#f6f6f6",blockquoteColor: "rgba(0,0,0,0.80)",icon: "#121212"}
};

This just happens to be the color pallette I use for my blog, but really the sky is the limit when it comes to themes, so feel free to experiment.

这恰好是我在博客中使用的彩色调色板,但实际上在主题方面,天空是极限,所以请随时尝试。

Now we create our ThemeSelectorContext:

现在,我们创建ThemeSelectorContext

export const ThemeSelectorContext = React.createContext({themeName: "dark",toggleTheme: () => {}
});

And our theme component:

还有我们的主题组件:

export default ({ children }) => {const [themeName, setThemeName] = useState("dark");const [theme, setTheme] = useState(themes[themeName]);const toggleTheme = () => {if (theme === themes.dark) {setTheme(themes.light);setThemeName("light");} else {setTheme(themes.dark);setThemeName("dark");}};return (<ThemeSelectorContext.Provider value={{ toggleTheme, themeName }}>{children}</ThemeSelectorContext.Provider>);
};

In this component we store our selected theme object, and the selected theme name, and we defined a function to toggle our selected theme.

在此组件中,我们存储选定的主题对象和选定的主题名称,并定义了一个函数来切换选定的主题。

The last bit left is actually setting the CSS custom properties from our theme. We can easily do it using the .style.setProperty API:

最后剩下的实际上是从我们的主题设置CSS自定义属性。 我们可以使用.style.setProperty API轻松完成此操作:

const setCSSVariables = theme => {for (const value in theme) {document.documentElement.style.setProperty(`--${value}`, theme[value]);}
};

Now for each value in our theme object we can access a CSS property with the same name (prefixed with -- of course). The last thing we need is to run the setCSSVariables function every time the theme is toggled. So in our Theme component we can use the useEffect hook like so:

现在,对于theme对象中的每个值,我们可以访问具有相同名称CSS属性(当然,前缀为-- )。 我们需要做的最后一件事是每次切换主题时都运行setCSSVariables函数。 因此,在我们的Theme组件中,我们可以像这样使用useEffect钩子:

export default ({ children }) => {// code...useEffect(() => {setCSSVariables(theme);});// code...
};

The full source code can be found on github.

完整的源代码可以在github上找到。

Using our theme is super convenient:

使用我们的主题非常方便:

.title {color: var(--primary);
}

And updating our theme is just as easy:

并且更新主题同样容易:

import Toggle from "react-toggle";export default () => {const { toggleTheme, themeName } = useContext(ThemeSelectorContext);return <Toggle defaultChecked={themeName === "dark"} onClick={toggleTheme} />;
};

For this example I'm using the Toggle component from react-toggle, but any toggle/button component would do just fine. Clicking the Toggle will call the toggleTheme function, and will update our theme for the entire app, no more configuration needed.

对于此示例,我使用了react-toggleToggle组件,但是任何toggle / button组件都可以。 单击“ Toggle将调用toggleTheme函数,并将更新整个应用程序的主题,无需进行其他配置。

That's it! That's all you need to do to create a super simple, super clean theme engine for your application. If you want to see a real live example, you can check out the source code of my blog.

而已! 这就是为您的应用程序创建超级简单,超级干净的主题引擎所需要做的一切。 如果您想看一个真实的例子,可以查看我博客的源代码 。

Thank you for reading!

感谢您的阅读!

This article was previously published on my blog: dorshinar.me. If you want to read more content, you can check my blog as it would mean a lot to me.

该文章先前已发布在我的博客dorshinar.me上 。 如果您想内容,可以查看我的博客,因为这对我来说意义重大。

翻译自: https://www.freecodecamp.org/news/themes-using-css-variables-and-react-context/

react css多个变量

react css多个变量_如何使用CSS变量和React上下文创建主题引擎相关推荐

  1. vue css 应用变量_如何使用CSS Grid和CSS变量快速为应用创建原型

    vue css 应用变量 CSS Grid and CSS Variables are both huge wins for front-end developers. The former make ...

  2. css 变量_如何将CSS变量用于动画

    css 变量 当我们在讨论中提到CSS时,我们通常将其称为愚蠢的语言. 一种声明性语言,缺乏逻辑和洞察力: 但这不是真实的现实. 多年来,开发人员一直渴望标准CSS中的变量,长期以来一直被诸如LESS ...

  3. MySQL数据库变量_数据库参数_MySQL变量_系统变量_用户变量

    文章目录 MySQL 变量分类 系统变量 查看系统变量 设置系统变量 如何通过配置文件来设置变量值 通过命令行选项来设置变量值 动态设置全局级的系统变量 设置静态的系统变量 设置会话级的系统变量 引用 ...

  4. frame中src怎么设置成一个变量_自动格式化打印变量HMLog介绍

    作者 | mao2020 来源 | 掘金,点击阅读原文查看作者更多文章 前言 在我初学iOS的时候,经常需要NSLog打印用于调试,有时候还需要打印多个变量: NSLog(@"xxxx fr ...

  5. 环境变量_配置JAVA环境变量

    本文标识 :  J00001本文编辑 :  YiKi编程工具 :  IDEA阅读时长 :  3分钟 什么是环境变量?环境变量是在操作系统中一个具有特定名字的对象, 它包含了一个或者多个应用程序所将使用 ...

  6. css左右布局代码_如何使用CSS位置来布局网站(带有示例代码)

    css左右布局代码 Using CSS position to layout elements on your website can be hard to figure out. What's th ...

  7. java设置系统环境变量_设置java 环境变量

    DOS下任意目录用JAVA,JAVAC肯定是显示正确咯,因为你设置好了JAVAlib和bin的但是JAVA文件需要DOS下CD好了目录才能JAVAC否则是在C:\program里查找该JAVA文件你任 ...

  8. css hover变成手_如何用CSS设置连接鼠标在上面是变成手型

    展开全部 用CSS设置连接鼠标在上面变成手型的方法:只需要对需32313133353236313431303231363533e59b9ee7ad9431333365666238要设置鼠标指针的文字加 ...

  9. python 分类变量转为哑变量_机器学习笔记——哑变量处理

    在机器学习的特征处理环节,免不了需要用到类别型特征,这类特征进入模型的方式与一般数值型变量有所不同. 通常根据模型的需要,类别型特征需要进行哑变量处理,即按照特征类别进行编码,一般一个类别为k的特征需 ...

最新文章

  1. 解决打包软链接打包失败问题
  2. mongodb-创建索引
  3. 797C C. Minimal string
  4. MongoDB对文档的操作
  5. wordpress mysql 密码重置_WordPress忘记密码找回登录密码的四种行之有效的方法
  6. 信息学奥赛一本通(2033:【例4.19】阶乘之和)
  7. 【算法】剑指 Offer 25. 合并两个排序的链表
  8. 在Java中将字符串转换为char数组,将char数组转换为String
  9. 网页怎么调用云服务器资源,如何将网页资源放到云服务器
  10. 计算机目录的制作步骤,怎么用word2003制作目录
  11. 怎么生成html链接,终于认识如何创建网页超链接
  12. 5款超棒的微信小程序!绝对满足你的需求!个个超级厉害!
  13. 深入理解Spring框架的作用
  14. 只有rear指针的环形循环队列
  15. STM32蓝牙控制LED灯开关
  16. 蚂蚁区块链平台BaaS技术解析与实践
  17. 把照片做成计算机符号,把家驹的照片做成了符号的形式
  18. Zabbix使用SMTP发送邮件报警并且制定报警内容
  19. 谷歌中一些十分有趣的特效现象
  20. STM32F103xx OLED旋转显示图片

热门文章

  1. 互联网寒冬!技术站最全MySQL数据库实战规范
  2. 网易严选Java开发三面面经:南京黑马java培训怎么样
  3. 灵魂拷问!一起刷完了这份1307页的安卓面试宝典吧,不吃透都对不起自己
  4. 知乎上已获千赞,全网独家首发!
  5. win10计算机磁盘图标,Win10 21H1怎么更换电脑磁盘的图标标识
  6. C++11并发编程:多线程std::thread
  7. dev中文本框等获取焦点事件
  8. 运用Appium 实现添加微信好友自动化
  9. 12.8 线程和信号
  10. IOS CALayer的属性和使用