将暗模式添加到您的React项目

Dark mode gives users the power to control their own experience when using your site — giving them a better user experience. For this reason, you might be interested in adding a dark mode feature to your website. I’m going to take you through one possible way of adding a dark mode feature to your React site.

暗模式使用户可以在使用您的网站时控制自己的体验,从而获得更好的用户体验。 因此,您可能有兴趣向网站添加暗模式功能。 我将带您通过一种可能的方式向您的React站点添加暗模式功能。

I’m starting with a new project created by running npx create-react-app my-app, but you can follow this tutorial with any existing React project.

我从运行npx create-react-app my-app创建的新项目开始,但是您可以将本教程与任何现有的React项目一起阅读。

To get a toggle-able dark mode feature throughout our entire project, we’re going to need to create a “global style”. Luckily, styled-component has a great helper function -createGlobalStyle — to easily handle global styling. Styled components are typically scoped automatically to a local CSS class, but using createGlobalStyle removes this limitation. To add styled-component to your project, run npm install styled-component

为了在整个项目中获得可切换的黑暗模式功能,我们将需要创建“全局样式”。 幸运的是,样式化组件具有强大的辅助功能-createGlobalStyle-可轻松处理全局样式。 样式化组件通常自动作用域为本地CSS类,但是使用createGlobalStyle可以消除此限制。 要将样式组件添加到项目中,请运行npm install样式组件

Now that we have styled-component installed and ready to use, let’s create our global style file. Create a new src>styles folder, and inside create a new file globalStyles.js. Inside the file, we want to use styled-component’s createGlobalStyle function, as well as define our constant colors for light vs dark theme. Defining a transition here will create a gradual linear change in background color when toggling between light and dark mode.

现在我们已经安装了样式组件,并且可以使用了,让我们创建全局样式文件。 创建一个新的src> styles文件夹,并在内部创建一个新文件globalStyles.js。 在文件内部,我们要使用样式组件的createGlobalStyle函数,并为浅色和深色主题定义恒定的颜色。 在明亮和黑暗模式之间切换时,在此处定义过渡将在背景颜色中逐渐形成线性变化。

import { createGlobalStyle} from "styled-components"


export const GlobalStyles = createGlobalStyle`
  body {
    background: ${({ theme }) => theme.body};
    color: ${({ theme }) => theme.text};
    transition: all 1.0s linear;
  }
  `
  
export const lightTheme = {
    body: '#FFF',
    text: '#000',
}


export const darkTheme = {
    body: '#000',
    text: '#FFF',
}

Next up, we want to create a custom hook to enable us to use dark mode. In the styles folder, create another new file called useDarkMode.js. Here, you’ll manage the theme value (I used dark as my default) and how it changes.

接下来,我们要创建一个自定义钩子,使我们能够使用暗模式。 在样式文件夹中,创建另一个名为useDarkMode.js的新文件。 在这里,您将管理主题值(我将Dark用作默认值)及其更改方式。

import { useEffect, useState } from 'react';


export const useDarkMode = () => {
    const [theme, setTheme] = useState('dark');
    const [mountedComponent, setMountedComponent] = useState(false)


    const setMode = mode => {
        window.localStorage.setItem('theme', mode)
        setTheme(mode)
    };


    const toggleTheme = () => {
        theme === 'dark' ? setMode('light') : setMode('dark')
    };


    useEffect(() => {
        const localTheme = window.localStorage.getItem('theme');
        localTheme ? setTheme(localTheme) : setMode('dark')
        setMountedComponent(true)
    }, []);


    return [theme, toggleTheme, mountedComponent]
};

Now, we want to create a Toggle component, where users will click to toggle between light and dark. Let’s create a new src>components folder, where we can create a new file Toggle.js. Inside Toggle, we want to create a component that displays a sun or a moon svg image depending on the current theme.

现在,我们要创建一个Toggle组件,用户将在其中单击以在明暗之间切换。 让我们创建一个新的src> components文件夹,在其中可以创建一个新文件Toggle.js。 在Toggle内部,我们要创建一个组件,该组件根据当前主题显示太阳或月亮svg图像。

import React from 'react'
import styled from "styled-components"


var Sun, Moon


Sun = Moon = styled.svg`
 transition: all 1.0s linear;
`;


const Toggle = ({theme,  toggleTheme }) => {
    return (
      <div onClick={toggleTheme}>
        {theme === "light" ?
          <Moon xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#212121" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-moon"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></Moon>
          : <Sun xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-sun"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></Sun>}
      </div>
    );
};


export default Toggle;

The last step is to put everything together in App.js. If you used create-react-app to get started with your project, make sure to remove some of the default styling so that our new global styling doesn’t get overwritten. In the App.css folder, remove the background-color and color fields from className App-header.

最后一步是将所有内容整合到App.js中。 如果您使用create-react-app来开始项目,请确保删除一些默认样式,以免新的全局样式被覆盖。 在App.css文件夹中,从className App-header中删除background-color和color字段。

Inside App.js, we have to import our newly created files, as well as ThemeProvider from styled-components. We want to call our custom useDarkMode hook here to set the initial state. We also need to wrap our JSX code withThemeProvider, and add in our GlobalStyles. I added my toggle directly under the React logo, but feel free to put it anywhere inside the page. My completed App.js file looks like this:

在App.js中,我们必须从样式组件中导入我们新创建的文件以及ThemeProvider。 我们要在此处调用自定义useDarkMode钩子以设置初始状态。 我们还需要用ThemeProvider包装JSX代码,并添加GlobalStyles。 我直接在React徽标下添加了切换开关,但可以随时将其放置在页面内的任何位置。 我完成的App.js文件如下所示:

import React from 'react';
import logo from './logo.svg';
import './App.css';
import {ThemeProvider} from "styled-components";
import  {useDarkMode} from "./styles/useDarkMode";
import { GlobalStyles, lightTheme, darkTheme } from "./styles/globalStyles";
import Toggle from "./components/Toggle";


function App() {


  const [theme, toggleTheme, mountedComponent] = useDarkMode();
  const themeMode = theme === 'light' ? lightTheme : darkTheme;


  if(!mountedComponent) return <div/>
  
  return (
    <ThemeProvider theme={themeMode}>
    <GlobalStyles/>
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <Toggle theme={theme} toggleTheme={toggleTheme} />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
    </ThemeProvider>
  );
}


export default App;

If you haven’t already, start your project with yarn start. And you’re done!

如果还没有,请使用yarn start启动项目。 大功告成!

If you haven’t already, start your project with yarn start to test out your new dark mode features. And you’re done!

如果还没有,请从yarn开始您的项目,以测试新的暗模式功能。 大功告成!

I hope this tutorial helped you :) you can find the full repo here!

希望本教程对您有所帮助:)您可以在此处找到完整的仓库

翻译自: https://medium.com/javascript-in-plain-english/adding-dark-mode-to-your-react-project-21b98fd852b0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值