728x90
๐ props, onClick, handleClick ์์ธํ๊ฒ ์ดํดํ๊ธฐ
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>;
};

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>;
};

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>;
};

๋ฐ์ํ
๋๊ธ