๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Frontend/React

[ ๋ฆฌ์•กํŠธ(React) ] props, onClick, handleClick ์ž์„ธํ•˜๊ฒŒ ์ดํ•ดํ•˜๊ธฐ

by YWTechIT 2021. 5. 15.
728x90

๐Ÿ“ props, onClick, handleClick ์ž์„ธํ•˜๊ฒŒ ์ดํ•ดํ•˜๊ธฐ

  1. Button ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ชจ๋“ˆํ™”(module)์‹œํ‚ฌ ๋•Œ ์ด๋ฆ„์„ ๋ฐ”๋กœ ์ •ํ•˜์ง€ ๋ง๊ณ  props๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์œ„์—์„œ ๊ฐ’์„ ์„ค์ •ํ•ด์„œ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๊ฒŒ ๋” ์„ค์ •ํ•˜์ž. ๋‹ค์Œ์€ Button ์ปดํฌ๋„ŒํŠธ๋ฅผ ์™ธ๋ถ€์—์„œ ์‚ฌ์šฉํ•  ๋•Œ props๋กœ button์˜ ์ด๋ฆ„์„ ๋ณ€๊ฒฝํ•˜๋Š” ๊ฐ„๋‹จํ•œ ๊ธฐ๋Šฅ์ด๋‹ค.
// components/App.js
const App = () => {
    return <Button text="IT IS BUTTON"></Button>;
};

// components/Button/index.js
const Button = (props) => {
  return <button>{props.text}</button>;
};

 

  1. Button ์ปดํฌ๋„ŒํŠธ์— handleClick ๊ธฐ๋Šฅ์„ ๋‹ฌ์•„์ฃผ๊ณ  ์‹ถ์„ ๋•Œ๋Š” ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ handleClick ์ปดํฌ๋„ŒํŠธ๋ฅผ props๋กœ ๋‚ด๋ ค์ฃผ๋ฉด ๋œ๋‹ค. ๋‹ค๋งŒ props๋กœ ๋ฐ›๊ณ ๋‚˜์„œ props.onClick()์ฒ˜๋Ÿผ ๊ด„ํ˜ธ(())๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํด๋ฆญํ–ˆ์„ ๋•Œ ํ•จ์ˆ˜๋ฅผ ๋ฐ”๋กœ ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ด„ํ˜ธ(())๋ฅผ ๋„ฃ์ง€ ์•Š์œผ๋ฉด ์˜ค๋ฅ˜๊ฐ€ ๋‚œ๋‹ค.
728x90

 

// src/components/Button/index.js
const Button = (props) => {
  return (
    <button
      onClick={() => {
        console.log(" i'm button. ");
        props.onClick();
      }}
    >
      {props.text}
    </button>
  );
};

// src/components/App.js
const App = () => {
    const handleClick = () => {
        console.log(" i'm handleClick!. ")
    }
  return <Button text="IT IS BUTTON" onClick={handleClick}></Button>;
};

 

 

  1. handleClick์„ ๋‹ค๋ฅธ ํ•จ์ˆ˜์— ๋„ฃ์–ด๋‘๊ณ  ๊ทธ ํ•จ์ˆ˜๋ฅผ ์ ์šฉํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ž‘์„ฑํ•˜๋ฉด ๋œ๋‹ค. ์ด๋•Œ์—๋„ ๊ด„ํ˜ธ(())๋ฅผ ๋„ฃ์–ด์ฃผ๋Š”๊ฒƒ์„ ์žŠ์ง€ ๋ง์ž!
// src/components/Button/index.js
const Button = (props) => {
  return (
    <button
      onClick={() => {
        console.log(" i'm button. ");
        props.onClick();
      }}
    >
      {props.text}
    </button>
  );
};

// src/components/App.js
const App = () => {
    const handleClick = () => {
        console.log(" i'm handleClick!. ")
    }

    const handleClick2 = () => {
        handleClick();
    }

  return <Button text="IT IS BUTTON" onClick={handleClick2}></Button>;
};

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€