본문 바로가기
Front-end/React\RN

React 리액트 props 속성 전달과 구조분해할당

by javapp 자바앱 2024. 3. 5.
728x90

 

 

리액트를 배우면서 굉장히 유용하고 꿀 코드들을 정리하려고 합니다.

 

 

구조분해할당
은 JavaScript와 다른 프로그래밍 언어에서 사용되는 문법입니다. 이를 통해 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 됩니다.

 

props

기본사용 

function CoreConcept(props) {
  return (
    <li>
      <img src={props.image} alt=".." />
      <h3>{props.title}</h3>
      <p>{props.description}</p>
    </li>
  );
}

이 함수는 props object를 가져와서 값을 구성하는 컴포넌트 입니다.

 

 

App 함수 

          <ul>
            <CoreConcept
              title={CORE_CONCEPTS[0].title} // props
              description="UI 블록"
              image={componentsImg}
            />

CoreConcept 컴포넌트에 object 를 만들어 호출하고

function CoreConcept(props) 에서 받습니다.

 

해당 값들은 또한 별도의 파일로 저장하여 사용할 수 있습니다.

 


 

별도 파일로 사용

data.js

import componentsImg from "./assets/components.png";
import propsImg from "./assets/config.png";
import jsxImg from "./assets/jsx-ui.png";
import stateImg from "./assets/state-mgmt.png";

export const CORE_CONCEPTS = [
  {
    image: componentsImg,
    title: "Components",
    description:
      "The core UI building block - compose the user interface by combining multiple components."
  },
  {
    image: jsxImg,
    title: "JSX",
    description:
      "Return (potentially dynamic) HTML(ish) code to define the actual markup that will be rendered."
  },
  ...

 

 

App.jsx

import { CORE_CONCEPTS } from "./data.js";

 

 

사용

title={CORE_CONCEPTS[0].title} // props

 

 

 

파일 

import componentsImg from "./assets/components.png";

 

사용

image={componentsImg}

 

 


 

구조 분해 사용

기존

function CoreConcept(props) {
  return (
    <li>
      <img src={props.image} alt=".." />
      <h3>{props.title}</h3>
      <p>{props.description}</p>
    </li>
  );
}

 

구조분해 적용 

function CoreConcept({ image, title, description }) {
  return (
    <li>
      <img src={image} alt={title} />
      <h3>{title}</h3>
      <p>{description}</p>
    </li>
  );
}

이 때, value값이 맞아야 됩니다.

 

※ 기본값 적용할 경우

function Button({ caption, type = "submit" })

 

 

 

 

 

 

 

댓글