๋ฆฌ์•กํŠธ(React)

ํด๋ž˜์Šคํ˜• component์™€ ํ•จ์ˆ˜ํ˜• component

changy0ng 2022. 7. 24. 11:11

๐ŸŽ์ปดํฌ๋„ŒํŠธ(Component) 

์ปดํฌ๋„ŒํŠธ๋Š” ์šฐ์„  ๋ถˆ๋ก์ด๊ณ  ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค

์ปดํฌ๋„ŒํŠธ = ํ™”๋ฉด์„ ๊ตฌ์„ฑํ•˜๋Š” ํ•˜๋‚˜์˜ ๋‹จ์œ„

 

๋ ˆ๊ณ  ๋ธ”๋ก์„ ์ฝ”๋“œ๋กœ ๋งŒ๋“ค๋ฉด

// App ์ปดํฌ๋„ŒํŠธ

function App (){
return <div></div>
}

 

๋ฆฌ์•กํŠธ ์„ธ๊ณ„์—์„œ ๋งํ•˜๋Š” ์ปดํฌ๋„ŒํŠธ๋Š” ํ•จ์ˆ˜
์ปดํฌ๋„ŒํŠธ๋ฅผ ๋งŒ๋“ค๋ผ๊ณ  ํ•œ๋‹ค๋ฉด ์šฐ๋ฆฌ๋Š” html์„ return ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค๋ฉด๋œ๋‹ค

 

๐Ÿ‘‰ ๋ฆฌ์•กํŠธ์—์„œ ์ปดํฌ๋„ŒํŠธ๋Š” ํด๋ž˜์Šคํ˜• Component์™€ ํ•จ์ˆ˜ํ˜• Component๊ฐ€ ์žˆ์œผ๋ฉฐ ๋‘˜์˜ ์ฐจ์ด์ ์€ ์ƒํƒœ๊ฐ’๊ณผ Life Cycle์˜ ์œ ๋ฌด์— ๋”ฐ๋ผ ๋‹ค๋ฆ…๋‹ˆ๋‹ค. ๐Ÿ’ฅ ํ•˜์ง€๋งŒ ๋ฆฌ์•กํŠธ ๋ฒ„์ „ 16.8๋ถ€ํ„ฐ๋Š” ํ›…(Hook)์— ์˜ํ•ด ํ•จ์ˆ˜ํ˜• ์ปดํฌ๋„ŒํŠธ์—์„œ๋„ ์ƒํƒœ๊ฐ’๊ณผ ์ƒ๋ช… ์ฃผ๊ธฐ ํ•จ์ˆ˜ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

 

๐Ÿ“Œํด๋ž˜์Šคํ˜• Component 

 

๐ŸŸฅ ํด๋ž˜์Šคํ˜• ์ปดํฌ๋„ŒํŠธ๋Š” ์ƒํƒœ๊ฐ’์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ์œผ๋ฉฐ ๋ฆฌ์•กํŠธ ์ปดํฌ๋„ŒํŠธ์˜ ์ƒ๋ช… ์ฃผ๊ธฐ ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.ํŠน์ง•์€

๐Ÿ‘‰ class ํ‚ค์›Œ๋“œ๋กœ ์‹œ์ž‘ํ•œ๋‹ค

๐Ÿ‘‰ Component๋กœ ์ƒ์†๋ฐ›๋Š”๋‹ค

๐Ÿ‘‰ render() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ JSX๋กœ ๋ฐ˜ํ™˜ํ•œ๋‹ค

๐Ÿ‘‰ props๋ฅผ ์กฐํšŒํ• ๋•Œ๋Š” this ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค

import React, { Component } from 'react';

class Hello extends Component {
  render() {
    const { color, name, isSpecial } = this.props;
    return (
      <div style={{ color }}>
        {isSpecial && <b>*</b>}
        ํ•˜์ด {name}
      </div>
    );
  }
}

export default Hello;

๐ŸŸฅ defaultProps ์„ค์ •์‹œ์—๋Š” ํด๋ž˜์Šค ๋‚ด๋ถ€์— static ํ‚ค์›Œ๋“œ์™€ ํ•จ๊ป˜ ์„ ์–ธํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค.

import React, { Component } from 'react';

class Hello extends Component {
  // defaultProps ์ฒซ๋ฒˆ์งธ ์„ค์ • ๋ฐฉ๋ฒ•
  static defaultProps = {
    name: '์ด๋ฆ„์—†์Œ'
  };
  
  render() {
    // ...
    );
  }

  // defaultProps ๋‘๋ฒˆ์งธ ์„ค์ • ๋ฐฉ๋ฒ•
Hello.defaultProps = {
  name: '์ด๋ฆ„์—†์Œ'
};
}

export default Hello;