react css多個變量_如何使用CSS變量和React上下文創建主題引擎

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變量是我們定義將在整個應用程序中應用的變量的一種方式。 語法如下:

CSS Variables

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上 。 如果您想內容,可以查看我的博客,因為這對我來說意義重大。

Buy Me a Coffee at ko-fi.com

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

react css多個變量

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390681.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390681.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390681.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

vue 自定義 移動端篩選條件

1.創建組件 components/FilterBar/FilterBar.vue <template><div class"filterbar" :style"{top: top px}"><div class"container"><div class"row"><divclass"col":class"{selected: ind…

PSP

姓名&#xff1a;袁亞琴 日期&#xff1a;11月27日 教師&#xff1a;王建民 課程&#xff1a;PSP 項目計劃日志&#xff1a; PSP Planning . Estimate Development . Analysis . Design Spec . Design Review . …

如何在Windows中打開和使用命令提示符

入門 (Getting started) Windows, MacOS and Linux have command line interfaces. Windows’ default command line is the command prompt. The command prompt allows users to use their computer without pointing and clicking with a mouse. Windows&#xff0c;MacOS和…

ACM-ICPC北京賽區2017網絡同步賽H

http://hihocoder.com/contest/icpcbeijing2017/problem/8 預處理暴力枚舉修改的點 #include <bits/stdc.h> using namespace std; const int maxn 159; const int inf 0x3f3f3f3f; int a[maxn][maxn]; int colsum[maxn][maxn]; int rowsum[maxn][maxn]; int dp[maxn];…

PPPOE撥號上網流程及密碼竊取具體實現

樓主學生黨一枚&#xff0c;最近研究netkeeper有些許心得。 關于netkeeper是調用windows的rasdial來進行上網的東西&#xff0c;網上已經有一大堆&#xff0c;我就不贅述了。 本文主要講解rasdial的部分核心過程&#xff0c;以及我們可以利用它來干些什么。 netkeeper中rasdial…

leetcode 160. 相交鏈表(雙指針)

給你兩個單鏈表的頭節點 headA 和 headB &#xff0c;請你找出并返回兩個單鏈表相交的起始節點。如果兩個鏈表沒有交點&#xff0c;返回 null 。 圖示兩個鏈表在節點 c1 開始相交&#xff1a; 題目數據 保證 整個鏈式結構中不存在環。 注意&#xff0c;函數返回結果后&#…

android開發入門_Android開發入門

android開發入門Android is an open source, Linux-based mobile operating system. Android was developed by the Open Handset Alliance, which was lead by Google and featured contributions from many other companies.Android是基于Linux的開放源代碼移動操作系統。 An…

新購阿里云服務器ECS創建之后無法ssh連接的問題處理

作者&#xff1a;13 GitHub&#xff1a;https://github.com/ZHENFENG13 版權聲明&#xff1a;本文為原創文章&#xff0c;未經允許不得轉載。 問題描述 由于原服務器將要到期&#xff0c;因此趁著阿里云搞促銷活動重新購買了一臺ECS服務器&#xff0c;但是在初始化并啟動后卻無…

數據下發非標準用戶權限測試

與同事一起溝通了下MDM的Oracle權限部分: create user cx default tablespace cwbaseoe73 identified by Test6530 grant select,update,delete,insert on lcoe739999.lsbzdw to cx grant create table to cx alter user cx quota unlimited on cwbaseoe73 grant create sessio…

leetcode 474. 一和零(dp)

給你一個二進制字符串數組 strs 和兩個整數 m 和 n 。 請你找出并返回 strs 的最大子集的大小&#xff0c;該子集中 最多 有 m 個 0 和 n 個 1 。 如果 x 的所有元素也是 y 的元素&#xff0c;集合 x 是集合 y 的 子集 。 示例 1&#xff1a; 輸入&#xff1a;strs [“10”…

邊緣計算 ai_在邊緣探索AI!

邊緣計算 ai介紹 (Introduction) What is Edge (or Fog) Computing?什么是邊緣(或霧)計算&#xff1f; Gartner defines edge computing as: “a part of a distributed computing topology in which information processing is located close to the edge — where things a…

JavaScript中的全局變量介紹

Global variables are declared outside of a function for accessibility throughout the program, while local variables are stored within a function using var for use only within that function’s scope. If you declare a variable without using var, even if it’…

初識spring-boot

使用Spring或者SpringMVC的話依然有許多東西需要我們進行配置&#xff0c;這樣不僅徒增工作量而且在跨平臺部署時容易出問題。 使用Spring Boot可以讓我們快速創建一個基于Spring的項目&#xff0c;而讓這個Spring項目跑起來我們只需要很少的配置就可以了。Spring Boot主要有如…

leetcode 879. 盈利計劃(dp)

這是我參與更文挑戰的第9天 &#xff0c;活動詳情查看更文挑戰 題目 集團里有 n 名員工&#xff0c;他們可以完成各種各樣的工作創造利潤。 第 i 種工作會產生 profit[i] 的利潤&#xff0c;它要求 group[i] 名成員共同參與。如果成員參與了其中一項工作&#xff0c;就不能…

區塊鏈101:區塊鏈的應用和用例是什么?

區塊鏈技術是一場記錄系統的革命。 比特幣是歷史上第一個永久的、分散的、全球性的、無信任的記錄分類帳。自其發明以來&#xff0c;世界各地各行各業的企業家都開始明白這一發展的意義。 區塊鏈技術的本質讓人聯想到瘋狂&#xff0c;因為這個想法現在可以應用到任何值得信賴的…

java請求接口示例_用示例解釋Java接口

java請求接口示例介面 (Interfaces) Interface in Java is a bit like the Class, but with a significant difference: an interface can only have method signatures, fields and default methods. Since Java 8, you can also create default methods. In the next block y…

如何建立搜索引擎_如何建立搜尋引擎

如何建立搜索引擎This article outlines one of the most important search algorithms used today and demonstrates how to implement it in Python in just a few lines of code.本文概述了當今使用的最重要的搜索算法之一&#xff0c;并演示了如何僅用幾行代碼就可以在Pyth…

用Docker自動構建紙殼CMS

紙殼CMS可以運行在Docker上&#xff0c;接下來看看如何自動構建紙殼CMS的Docker Image。我們希望的是在代碼提交到GitHub以后&#xff0c;容器鏡像服務可以自動構建Docker Image&#xff0c;構建好以后&#xff0c;就可以直接拿這個Docker Image來運行了。 Dockerfile 最重要的…

Linux學習筆記15—RPM包的安裝OR源碼包的安裝

RPM安裝命令1、 安裝一個rpm包rpm –ivh 包名“-i” : 安裝的意思“-v” : 可視化“-h” : 顯示安裝進度另外在安裝一個rpm包時常用的附帶參數有&#xff1a;--force : 強制安裝&#xff0c;即使覆蓋屬于其他包的文件也要安裝--nodeps : 當要安裝的rpm包依賴其他包時&#xff0…

leetcode 518. 零錢兌換 II

給定不同面額的硬幣和一個總金額。寫出函數來計算可以湊成總金額的硬幣組合數。假設每一種面額的硬幣有無限個。 示例 1: 輸入: amount 5, coins [1, 2, 5] 輸出: 4 解釋: 有四種方式可以湊成總金額: 55 5221 52111 511111 示例 2: 輸入: amount 3, coins [2] 輸出: 0 解…