본문 바로가기
Programming 개발은 구글로/Web[프론트엔드&백엔드]

[Web] React props & defaultProps 개념이해

by 40대직장인 2022. 6. 27.

React props & defaultProps 

1. props

: props는 부모 컴포넌트가 자식 컴포넌트에게 넘겨주는 값입니다.

 

<MyJob.js>

import React, { Component } from "react";

class MyJob extends Component {
    render() {
        return (
            <div>
                제 직업은 {this.props.job} 개발자입니다.
            </div>
        );
    }
}

export default MyJob;

자신이 받아온 props 값은 this. 키워드를 통하여 조회할 수 있습니다.

 

<App.js>

 

job = "Web"으로 props 값을 설정하였습니다.

import { Component } from 'react';
import MyJob from './MyJob'; // import MyJob

class App extends Component {
  render() {
    return (
      <MyJob job = "Web"/>
    );
  }
}

export default App;

Result: 제 직업은 Web 개발자입니다.

 

2. defaultProps

: 개발자 실수로 props 빠뜨릴 수 도 있고, 특정 상황에서 일부러 props를 비워둘 수도 있습니다. 이런 경우 props의 기본값을 설정할 수 있는데, 이것이 defaultProps입니다.

 

App.js 파일에서 <MyJob/>으로 받아서 job을 생략을 하면, 아래의 defaultProps로 설정이 됩니다.

import React, { Component } from "react";

class MyJob extends Component {
    static defaultProps = {
        job: "웹"
    }  
    render() {
        return (
            <div>
                제 직업은 {this.props.job} 개발자입니다.
            </div>
        );
    }
}

// MyJob.defaultProps = {
//     job: "기본이름"
// };

export default MyJob;

Result: 제 직업은 웹 개발자입니다.

 

※ 함수형 컴포넌트에서는 위의 코드에서 주석으로 처리된 방식으로 하시면 됩니다.

 

알기쉽게 profs 사용 예제를 올립니다.

 

<profs 적용 전>

import './App.css';

function Header() {
  return (
      <header>
        <h1><a href='/'>Web</a></h1>
      </header>
  )
}

function Nav() {
  return(
    <ol>
    <li><a href="/read/1">html</a></li>
    <li><a href="/read/2">css</a></li>
    <li><a href="/read/2">js</a></li>
    </ol>
  )
}

function Article() {
  return (
    <article>
    <h2>Hi</h2>
      Hello Teddy
    </article>
  )
}

function App() {
  return (
    <div>
      <Header></Header>
      <Nav></Nav>
      <Article></Article>
    </div>
  )
}

export default App;

 

 

<profs 적용 후>

import './App.css';

function Header(profs) {
  return (
      <header>
        <h1><a href='/'>{profs.title}</a></h1>
      </header>
  )
}

function Nav(profs) {
  const list = []
  for(let i=0; i<profs.topics.length; i++) {
    let t = profs.topics[i];
    list.push(<li><a href={'/read/'+t.id}>{t.title}</a></li>)
  }

   return <nav>
      <ol>
        {list}
      </ol>
    </nav>
   
}

function Article(profs) {
  return (
    <article>
    <h2>{profs.title}</h2>
      {profs.body}
    </article>
  )
}

function App() {
  const topics = [
    {id:1, title: 'html'},
    {id:2, title: 'css'},
    {id:3, title: 'js'}
  ]
  return (
    <div>
      <Header title = 'React'></Header>
      <Nav topics = {topics}></Nav>
      <Article title = "Bye" body="Go home"></Article>
    </div>
  )
}

export default App;

 

 


 

 

참고 글: 누구든지 하는 리액트 4편: props 와 state

https://velopert.com/3629

 

 

 

 

 

댓글