react 动态css
In this article we will cover the following:
在本文中,我们将介绍以下内容:
Adding custom colors and themes to tailwindcss. 向tailwindcss添加自定义颜色和主题。 Building a react application that uses the useContext React hook to store our theme. 构建一个使用useContext React钩子来存储主题的React应用程序。 Inline JavaScript to dynamically update our theme. 内联JavaScript以动态更新我们的主题。 Photo by Tianyi Ma on Unsplash 马天一在 Unsplash上的 照片Options:
选项:
You can clone my project here “Tailwind Theme Changer”.
您可以在“ Tailwind Theme Changer”中克隆我的项目。
You can follow this guide to build your own. 您可以按照本指南进行构建。First you need to set up a react project with tailwind css.
首先,您需要使用顺风CSS建立一个react项目。
You can either follow my Medium Article or I suggest going through the tailwind documentation to get tailwind css in your React project.
您可以关注我的中篇文章,也可以建议您阅读顺风文档,以在React项目中获得顺风CSS。
Inside src/ lets add a folder named utilities and inside that folder a file named ThemeContext.js.
里面的src /让我们添加一个文件夹命名为公用事业和内部的文件夹中的文件名为ThemeContext.js。
Inside src/ lets add another folder named pages and inside that folder a file named Home.js. (You could do all the code inside of App.js but I like to separate it out for ease of understanding)
在src /中,可以添加另一个名为pages的文件夹,并在该文件夹中添加一个名为Home.js的文件。 (您可以在App.js内完成所有代码,但为了便于理解,我想将其分开)
Lets add routing so we can access this file. Install react-router-dom to the project. 让我们添加路由,以便我们可以访问该文件。 在项目中安装react-router-dom。 npm i react-router-domInside your App.js import react router dom and lets add the following code.
在您的App.js内导入react router dom,并添加以下代码。
//App.jsimport React from "react";import { BrowserRouter, Route, Switch } from "react-router-dom";import "./assets/main.css";import Home from "./pages/Home";function App() {return (<div> <BrowserRouter> <Switch> <Route path='/' exact component={Home} /> </Switch> </BrowserRouter></div>);}export default App;Awesome this should be everything we need to get started.
太棒了,这应该是我们入门所需的一切。
In the root of your project you should have a file tailwind.config.js
在项目的根目录中,应该有一个文件tailwind.config.js
Lets add some of the things to it! Humor..
让我们添加一些东西吧! 幽默..
Lets add the theme: object 让我们添加主题:对象 Inside the theme add the extend: object 在主题内添加extend:对象 Inside the extend add the color: object 在扩展内添加color:对象From here you can call the theme any thing of your choosing
在这里,您可以随意选择主题
If you want to learn more about customizing tailwind check out their documentation here.
如果您想了解有关自定义顺风车的更多信息,请在此处查看其文档。
What is happening is we are essentially creating a color theme called dark and passing some values to each one of the number sets. When you build this it will build this CSS and you can pass these classes inline. For ex: bg-dark-100.
发生的事情是,我们实际上是在创建一个称为Dark的颜色主题,并将一些值传递给每个数字集。 当您构建它时,它将构建此CSS,您可以内联传递这些类。 例如:bg-dark-100。
//tailwind.config.jsmodule.exports = {plugins: [require("tailwindcss"),require("autoprefixer"),require("@tailwindcss/ui"),],theme: { extend: { colors: { dark: { 100: "#6d706f", 200: "#20c991", 300: "#ff1f4f", 400: "#dae0de", 500: "#ffffff", }, }, }, },};In the file we created in src/utilites/ThemeContext.js lets add the following code.
在我们在src / utilites / ThemeContext.js中创建的文件中,添加以下代码。
Import React. 导入React。 Export and create context. 导出并创建上下文。 Create a variable and dispatch using React.useState() hook. 创建一个变量并使用React.useState()钩子调度。 Create defaultContext and add our variable and dispatch. 创建defaultContext并添加变量和调度。 return our context and default context wrapping our children. 返回我们的上下文和包装我们孩子的默认上下文。 //ThemeContext.jsimport React from "react";export const ThemeContext = React.createContext();export default ({ children }) => {const [theme, setTheme] = React.useState('light')const defaultContext = {theme,setTheme};return (<ThemeContext.Provider value={defaultContext}>{children}</ThemeContext.Provider>);};Woot you’ve made it so far! Lets start putting that context to work
到目前为止,您已经做到了! 让我们开始使用该上下文
In our App.js we need to import context and wrap our routes and children in it so we have access to it.
在我们的App.js中,我们需要导入上下文并将路由和子级包装在其中,以便我们可以访问它。
//App.jsimport React from "react";import { BrowserRouter, Route, Switch } from "react-router-dom";import "./assets/main.css";import Home from "./pages/Home";import ThemeContext from "./utilities/ThemeContext";function App() {return (<ThemeContext> <BrowserRouter> <Switch> <Route path='/' exact component={Home} /> </Switch> </BrowserRouter></ThemeContext>);}export default App;In our Home.js we need to import our context so we can use our variable theme and dispatch setTheme.
在我们的Home.js中,我们需要导入上下文,以便可以使用变量主题并调度setTheme。
import React from "react";import { ThemeContext } from "../utilities/ThemeContext";export default function Home() {const { theme, setTheme } = React.useContext(ThemeContext);return ();}Lets do a quick recap of things we’ve done so far
让我们快速回顾一下到目前为止我们已经完成的事情
Built out files and file structure
建立文件和文件结构
Added a theme to our tailwind config
在我们的顺风配置中添加了一个主题
Created Context and imported it to App.js and Home.js
创建上下文并将其导入到App.js和Home.js
By now we’ve done a lot of setting up, here is where it all comes together.
到现在为止,我们已经完成了很多设置,这就是所有步骤的集合。
Lets open our Home.js file and
让我们打开Home.js文件并
add a function that updates our theme context 添加一个更新主题上下文的函数 add a button that uses that function 添加一个使用该功能的按钮 add an element to style 为样式添加元素 update className to be dynamic 更新className为动态To keep it simple here is what we are doing.
为了简单起见,这就是我们正在做的事情。
We are updating our context with our theme using a function onClick inside of a button. 我们正在使用按钮内的onClick函数以主题更新上下文。 We are then using that variable “theme” to dynamically update our theme in our className. 然后,我们使用变量“ theme”来动态更新className中的主题。 Here is how we do that inline. 这就是我们内联的方式。 className={`bg-${theme}-100`}So since our theme that we created in our tailwind config is named light. We can use a function to update that theme context variable to be “light” and use those colors.
因此,由于我们在顺风配置中创建的主题被命名为light。 我们可以使用函数将主题上下文变量更新为“浅色”并使用这些颜色。
Lets create the function to update our useContext variable theme.
让我们创建一个函数来更新我们的useContext变量主题。
const changeTheme = (event) => {setTheme(event.target.value);};Lets now create two buttons that will use this funciton and update the value to match our dark and light themes.
现在让我们创建两个将使用此功能的按钮,并更新该值以匹配我们的深色和浅色主题。
<buttononClick={changeTheme}value='light'className='px-1 py-1 rounded border border-black bg-white'>Light</button><buttononClick={changeTheme}value='dark'className='px-1 py-1 rounded border border-black bg-black text-white'>Dark</button>I’ve gone ahead and added all of them together. Feel free to copy the below code.
我已经将所有这些加在一起。 随时复制以下代码。
Please use prettier to format this.
请使用更漂亮的格式。
import React from "react";import { ThemeContext } from "../utilities/ThemeContext";export default function Home() {const { theme, setTheme } = React.useContext(ThemeContext);const changeTheme = (event) => {setTheme(event.target.value);};return (<div className='h-screen bg-gray-200'><div className='text-center w-full text-2xl '>React - Tailwind CSS - Theme Changer</div><div className='flex text-center my-8'><div className='mx-auto'><buttononClick={changeTheme}value='light'className='px-2 py-1 mr-1 rounded bg-white'>Light</button><buttononClick={changeTheme}value='dark'className='px-2 py-1 ml-1 rounded bg-black text-white'>Dark</button></div></div><div><div className={`bg-${theme}-100 shadow sm:rounded-lg mx-48`}><div className='px-4 py-5 sm:p-6'><h3 className={`text-${theme}-400 text-lg leading-6 font-medium`}>Payment method</h3><div className='mt-5'><divclassName={`bg-${theme}-300 shadow sm:rounded-lg rounded-md px-6 py-5 sm:flex sm:items-startsm:justify-between`}><div className='sm:flex sm:items-start'><svgclassName='h-8 w-auto sm:flex-shrink-0 sm:h-6'fill='none'viewBox='0 0 36 24'role='img'aria-labelledby='svg-visa'><title id='svg-visa'>VISA</title><rect width='36' height='24' fill='#224DBA' rx='4' /><pathfill='#fff'fill-rule='evenodd'd='M10.925 15.673H8.874l-1.538-6c-.073-.276-.228-.52-.456-.635A6.575 6.575 0 005 8.403v-.231h3.304c.456 0 .798.347.855.75l.798 4.328 2.05-5.078h1.994l-3.076 7.5zm4.216 0h-1.937L14.8 8.172h1.937l-1.595 7.5zm4.101-5.422c.057-.404.399-.635.798-.635a3.54 3.54 0 011.88.346l.342-1.615A4.808 4.808 0 0020.496 8c-1.88 0-3.248 1.039-3.248 2.481 0 1.097.969 1.673 1.653 2.02.74.346 1.025.577.968.923 0 .519-.57.75-1.139.75a4.795 4.795 0 01-1.994-.462l-.342 1.616a5.48 5.48 0 002.108.404c2.108.057 3.418-.981 3.418-2.539 0-1.962-2.678-2.077-2.678-2.942zm9.457 5.422L27.16 8.172h-1.652a.858.858 0 00-.798.577l-2.848 6.924h1.994l.398-1.096h2.45l.228 1.096h1.766zm-2.905-5.482l.57 2.827h-1.596l1.026-2.827z'clip-rule='evenodd'/></svg><div className='mt-3 sm:mt-0 sm:ml-4'><divclassName={`text-${theme}-400 text-sm leading-5 font-medium `}>Ending with 4242</div><div className='mt-1 text-sm leading-5 text-gray-600 sm:flex sm:items-center'><div>Expires 12/20</div><spanclassName='hidden sm:mx-2 sm:inline'aria-hidden='true'>·</span><div className='mt-1 sm:mt-0'>Last updated on 22 Aug 2017</div></div></div></div><div className='mt-4 sm:mt-0 sm:ml-6 sm:flex-shrink-0'><span className='inline-flex rounded-md shadow-sm'><buttontype='button'className={`bg-${theme}-500 text-${theme}-400 inline-flex items-center px-4 py-2 border border-gray-300 text-sm leading-5 font-medium rounded-md hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue active:text-gray-800 active:bg-gray-50 transition ease-in-out duration-150`}>Edit</button></span></div></div></div></div></div></div></div>);}You’ve made it!! Congrats you now have a react project that is set up for a light and dark theme. I plan on making more themes with this same methodology that I’ll include in my github repo.
你做到了! 恭喜,您现在有了一个针对明暗主题设置的react项目。 我计划使用将包含在github存储库中的相同方法制作更多主题。
As always please find me here and thanks for reading:
一如既往,请在这里找到我,并感谢您的阅读:
领英
My GitHub
我的GitHub
Link to project
链接到项目
翻译自: https://medium.com/@steven_creates/how-to-build-a-dynamic-theme-changer-with-react-and-tailwind-css-with-react-usecontext-hook-a0f818603f28
react 动态css
