Gatsby + React Project에서 다크 모드를 추가하는 방법!

스타일이 지정된 구성 요소



다크 테마를 추가하는 것은 웹뿐만 아니라 데스크탑, 네이티브 앱에서도 트렌드가 됩니다. 기존 프로젝트 또는 다음 프로젝트에 어두운 테마를 추가하면 몇 가지 이점이 있습니다. 어두운 테마는 화면에서 방출되는 빛을 줄여 독자가 밤에도 고통 없이 읽을 수 있도록 돕고 배터리 수명을 절약합니다...

시작하다



전제 조건, gatsby 프로젝트 및 일부 패키지를 설치하고 다음을 따르십시오.

gatsby new dark-mode

cd dark-mode/


install toggler, button

yarn add react-darkmode-toggler


또한 CSS-in-JS를 사용하려면 styled-components 패키지가 필요합니다.

yarn add styled-components


완료되면 이 시나리오에 사용할 vscode를 열고 /src/components/Theme/Theme.js라는 파일을 생성합니다. 거기에서 어둡고 밝은 테마 색상을 정의합니다.

export const darkTheme = {
  body: "#121212",
  surface: "#1D1D1D",
  font: "#D1D1D1",
}

export const lightTheme = {
  body: "#FFFFFF",
  surface: "#EEF2F5",
  font: "#2A292E",
}


보시다시피 어둠을 위한 두 개의 개체darkTheme와 빛(기본값)을 위한 lightTheme를 만들었습니다. 객체 buttonColor 및 hoverEffect와 darkTheme 색상.

이제 더미 데이터를 사용하기 위해 화면에 렌더링할 데이터가 필요합니다. lightTheme CSS라는 파일이 있는 폴더를 만들고 거기에 더미 데이터를 추가하고 Post를 사용하여 스타일을 지정할 수 있습니다.

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

const Row = styled.div`
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
`

const Col = styled.div`
  flex: 1 1 30%;
  max-width: 40%;
  margin: 10px;
  height: 150px;
  background: ${({ theme }) => theme.body};
  color: ${({ theme }) => theme.font};
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 10px;
  font-family: sans-serif;
`

export const Post = () => {
  return (
    <Row>
      {[1, 2, 3, 4, 5, 6, 8, 9].map(_ => (
        <Col key={_}>
          <h1>Hello, Gatsby</h1>
          <p>Love to use Gatsb and Learn cool stuff!</p>
          <p>Trying to Add Dark Theme in my Project!</p>
        </Col>
      ))}
    </Row>
  )
}

/src/components/Post/Post.js 및 2개의 styled-components 로 9개의 게시물을 렌더링하여 어두운 모드에서 h1를 변경하고 이전에 생성한 p 내부의 (테마 속성) 조명에서 color에 액세스할 수 있습니다(테마 속성).

배경색 변경, theme object , styled , background: ${ } 와 같은 테마 개체를 받는 화살표 기능이 필요합니다. 원하지만 아직 background: ${props => props.theme.body} 개체를 props.theme.body에 제공하지 않았으므로 Theme.js 루트 파일에서 수행하도록 합니다.

import React, { useState } from "react"
import { DarkModeToggler } from "react-darkmode-toggler"
import { Post } from "../components/Post/Post"

// Theme Provider
import styled, { ThemeProvider } from "styled-components"
import { lightTheme, darkTheme } from "../components/Theme/Theme"

/**
 * To center Toggler
 */
const Div = styled.div`
  margin: 20px auto;
  display: flex;
  justify-content: center;
`

export default () => {
  const [isDark, setIsDark] = useState("light")

  // Dark mode button toggler
  const darkModeHandler = () => {
    setIsDark(isDark === "light" ? "dark" : "light")
  }

  return (
    <ThemeProvider theme={isDark === "dark" ? darkTheme : lightTheme}>
      <GlobalStyle theme={isDark} />
      <Div>
        <DarkModeToggler
          size="small"
          isDark={isDark}
          onClick={darkModeHandler}
          border="#FFFFFF"
        />
      </Div>
      <Post />
    </ThemeProvider>
  )
}



당신은 그것을 가지고 있습니다! 하지만 HTMLbackground: ${({ theme }) => theme.body}; 색상도 변경해야 합니다. theme에 ThemeProvider를 생성해 보겠습니다.

import { createGlobalStyle } from "styled-components"
export const GlobalStyle = createGlobalStyle`
  body {
    background-color: ${props =>
      props.theme === 'dark' ? "#121212" : "#FFFFFF"};
  }`

/src/pages/index.js 아래의 body 에서 파일을 가져오고 다음과 같이 gloablStyle.js 소품을 전달합니다.

 <ThemeProvider theme={isDark === "dark" ? darkTheme : lightTheme}>
      <GlobalStyle theme={isDark} />
      /....
    </ThemeProvider>




내 게시물을 읽어 주셔서 감사합니다. Github repo for this project . 다음 게시물에서는 /src/components/Theme/를 통해 Dark 테마를 추가하고 @material-ui에 대해서도 안내해 드리겠습니다.

좋은 웹페이지 즐겨찾기