소품과 로컬 데이터를 사용하여 유연한 구성 요소를 만듭니다.

25706 단어 reactcodenewbiewebdev
이 기사에서는 재사용성과 소품에 초점을 맞추면서 자세히 살펴보고 리팩토링할 특정 구성 요소에 초점을 맞출 것입니다.

이것은 내 포트폴리오를 업데이트하고 작업이 필요한 정말 못생기고 비효율적인 구성 요소를 발견하면서 발생했습니다.

문제의 구성 요소는 이Projects 구성 요소였습니다. 다양한 프로젝트를 보여주기 위해 단순히 여러 카드 구성 요소ProjctCard를 렌더링했습니다. 각 카드는 다른 값으로 각각의 정보를 표시하기 위해 props를 받았습니다.

import React from 'react'
import ProjectCard from './components/ProjectCard'

// Project images
import kintsugi from '../images/kintsugi.png'
import agency from '../images/agency.jpg'
import merlin from '../images/merlins-marker.jpg'
import colorBurst from '../images/color-burst.jpg'
import coffeeHouse from '../images/coffee-house-screenshot.jpg'
import lightsOut from '../images/lights-out.jpg'

const Projects = () => (
  <>
    <ProjectCard
      img={kintsugi}
      title='Kintsugi'
      description='An Anime databse where users can browse and discover anime titles.'
      tech='NextJS | Tailwind CSS'
    />
    <ProjectCard
      img={agency}
      title='Agency'
      description='A simple landing page with a focus on minimal design and fluid animations using GSAP.'
      tech='React | GSAP'
    />
    <ProjectCard
      img={merlin}
      title='Merlins-Marker'
      description='A theme generator for Prism.js. Users create their own theme for code highlighting.'
      tech='JavaScript | CSS Variables'
    />
    <ProjectCard
      img={colorBurst}
      title='Color-Burst'
      description='A color palette generator to help users on their next project.'
      tech='React | React-Router | React-Sortable'
    />
    <ProjectCard
      img={coffeeHouse}
      title='Coffee House'
      description='A cofee/restaurant website.'
      tech='HTML/CSS | Sass | CSS Grid'
    />
    <ProjectCard
      img={lightsOut}
      title='Lights Out'
      description='A puzzle game in which you need to toggle all of the lights off.'
      tech='React'
    />
  </>
)

export default Projects


우리는 이 구성 요소가 효율성과 미래 보장이 부족하다는 것을 분명히 알 수 있습니다. 모든 소품은 수동으로 채워지고 각 카드가 계속해서 반복되기 때문에 코드는 DRY가 아닙니다.

At best, even if there were only two project cards to display, it's always beneficial to be intentional with the code you write and to think of use cases for the future.



이를 정리하기 위해 data 라는 새 폴더를 만든 다음 해당 폴더 안에 projectData.js 라는 새 파일을 만들 수 있습니다. 이 파일은 각각에 대한 소품 정보를 채우는 데 사용되는 모든 정적 데이터를 보유합니다ProjectCard.

export default [
  {
    img: kintsugi,
    title: 'Kintsugi',
    description: 'An Anime databse where users can browse and discover anime titles.',
    tech: 'NextJS | Tailwind CSS',
  },
  {
    img: agency,
    title: 'Agency',
    description: 'A simple landing page with a focus on minimal design and fluid animations using GSAP.',
    tech: 'React | GSAP',
  },
  {
    img: merlin,
    title: 'Merlins-Marker',
    description: 'A theme generator for Prism.js. Users create their own theme for code highlighting.',
    tech: 'JavaScript | CSS Variables',
  },
  {
    img: colorBurst,
    title: 'Color-Burst',
    description: 'A color palette generator to help users on their next project.',
    tech: 'React | React-Router | React-Sortable',
  },
  {
    img: coffeeHouse,
    title: 'Coffee House',
    description: 'A cofee/restaurant website.',
    tech: 'HTML/CSS | Sass | CSS Grid',
  },
  {
    img: lightsOut,
    title: 'Lights Out',
    description: 'A puzzle game in which you need to toggle all of the lights off.',
    tech: 'React',
  },
]


이 파일의 구조는 데이터를 매핑하고 각 개체 내의 값에 액세스할 수 있도록 하기 때문에 개체의 배열입니다.
projectData.js 파일에 추가해야 하는 또 다른 것은 모든 프로젝트 이미지입니다. 이를 통해 각 프로젝트와 관련된 모든 데이터에 대해 하나의 중앙 위치를 가질 수 있습니다.

// Project images
import kintsugi from '../images/kintsugi.png'
import agency from '../images/agency.jpg'
import merlin from '../images/merlins-marker.jpg'
import colorBurst from '../images/color-burst.jpg'
import coffeeHouse from '../images/coffee-house-screenshot.jpg'
import lightsOut from '../images/lights-out.jpg'

export default [
  {
    img: kintsugi,
    title: 'Kintsugi',
    description: 'An Anime databse where users can browse and discover anime titles.',
    tech: 'NextJS | Tailwind CSS',
  },
  {
    img: agency,
    title: 'Agency',
    description: 'A simple landing page with a focus on minimal design and fluid animations using GSAP.',
    tech: 'React | GSAP',
  },
  {
    img: merlin,
    title: 'Merlins-Marker',
    description: 'A theme generator for Prism.js. Users create their own theme for code highlighting.',
    tech: 'JavaScript | CSS Variables',
  },
  {
    img: colorBurst,
    title: 'Color-Burst',
    description: 'A color palette generator to help users on their next project.',
    tech: 'React | React-Router | React-Sortable',
  },
  {
    img: coffeeHouse,
    title: 'Coffee House',
    description: 'A cofee/restaurant website.',
    tech: 'HTML/CSS | Sass | CSS Grid',
  },
  {
    img: lightsOut,
    title: 'Lights Out',
    description: 'A puzzle game in which you need to toggle all of the lights off.',
    tech: 'React',
  },
]

Projects 구성 요소로 다시 이동하면 이제 하나를 제외한 ProjectCard 구성 요소의 모든 인스턴스를 제거할 수 있습니다. 이제 구성 요소는 다음과 같아야 합니다.

import React from 'react'
import ProjectCard from './components/ProjectCard'

const Projects = () => (
  <>
    <ProjectCard
      img={kintsugi}
      title='Kintsugi'
      description='An Anime databse where users can browse and discover anime titles.'
      tech='NextJS | Tailwind CSS'
    />
  </>
)

export default Projects


정적 소품 정보는 projectData.js 파일에서 제공되므로 더 이상 필요하지 않습니다. 이제 원하는 prop 값을 전달하면서 projectData.js 파일을 가져와 매핑할 수 있습니다.

import React from 'react'
import ProjectCard from './components/ProjectCard'
import data from '../data/projectData'

const Projects = () => (
  <>
    {data.map(project => (
      <ProjectCard
        key={project.title}
        img={project.img}
        title={project.title}
        description={project.description}
        tech={project.tech}
      />
    ))}
  </>
)

export default Projects


위에서 우리는 projectData.js 파일 내의 모든 객체로 표현되는 각 프로젝트를 매핑하고 데이터 객체의 키로 각 ​​prop 값을 채웠습니다.

data.map(project => (
  <ProjectCard
    key={project.title}
    img={project.img}
    title={project.title}
    description={project.description}
    tech={project.tech}
  />
))

key 속성이 추가되었음을 알 수 있습니다.

key={project.title}


이것은 React가 변경된 항목을 식별하는 방법을 제공하므로 구성 요소 목록을 렌더링할 때 필요합니다. 각 키는 고유해야 하므로 각 제목이 다르고 특정 ID가 없으므로 제목을 사용합니다.

마지막 단계는 단순히 프로젝트에서 prop 값을 구조화하는 것입니다.

import data from '../data/ProjectData'

const Projects = () => (
  <>
    {data.map(project => {
      let {img, title, description, tech} = project

      <ProjectCard
        key={title}
        img={img}
        title={title}
        description={description}
        tech={tech}
      />
    })}
  </>
)

export default Projects


이제 미래에 확장할 수 있는 읽기 쉽고 관리 가능한 구성 요소가 있습니다!

결론



Props는 컴포넌트가 수신하는 데이터에 적응할 수 있도록 하는 React의 필수 부분입니다. 지금까지 살펴본 바와 같이 디스플레이에서 데이터를 느슨하게 하여 보다 유연하고 집중적인 구성 요소를 제공하는 것이 항상 좋은 방법입니다.

이 글을 잘 보시고 가족과 함께 건강하시길 바랍니다!

좋은 웹페이지 즐겨찾기