[React] component와 props의 이해
1. component
💡 컴포넌트란 ?
어떠한 JSX를 반환하는 함수
아래 코드의SaveBtn()
ConfirmBtn()
App()
는 함수형 컴포넌트
// 함수형 컴포넌트
function SaveBtn() {
return <button>Save Changes</button>;
}
function ConfirmBtn() {
return <button>Confirm</button>;
}
function App() {
return (
// JSX 내부
<div>
<SaveBtn />
<ConfirmBtn />
</div>
);
}
2. props
⭐ props의 필요성
같은
style
을 같지만 기능이 다른 두 개의 버튼이 있다.
style
을 중복하여 코드를 작성하지 않고, 변경되는 부분(text)만 변경되도록 할 수는 없을까?
function SaveBtn() {
return (
<button
// 중복되는 style
style={{
backgroundColor: "tomato",
color: "white",
paddig: "10px 20px",
border: 0,
borderRadius: 10,
}}
>
// 변경되는 부분
Save Changes
</button>
);
}
function ConfirmBtn() {
return (
<button
// 중복되는 style
style={{
backgroundColor: "tomato",
color: "white",
paddig: "10px 20px",
border: 0,
borderRadius: 10,
}}
>
// 변경되는 부분
Confirm
</button>
);
}
✨props
란?
해당 함수가 전달받는 첫번째이자 유일한 인자
- 컴포넌트들은
( )
로argument
(인자)를 받음- 여기서 이
argument
(인자)를props
(properties)라고 부름props
는 아래 예제의 text와 같이 다양한 properties를 갖고 있는 객체
function Btn(props) {
return (
<button
style={{
backgroundColor: "tomato",
color: "white",
paddig: "10px 20px",
border: 0,
borderRadius: 10,
}}
>
{props.text}
</button>
);
}
function App() {
return (
<div>
// Btn의 properties인 text
<Btn text="Save Changes" />
<Btn text="Continue" />
</div>
);
}
✅ Btn( )함수를 불러 text라는 인자를
Btn({text:"save changes"})
와 같이 객체의 형태로 보냄
✅ 위 props는 객체의 형태로 Btn( )함수의 첫번째 인자로 들어감
💯 컴포넌트의 재사용을 가능하게 해준다!!
🎁 또다른 사용법
// 지름길! property를 object로부터 꺼내는 방법
function Btn({ text }) {
return (
<button
style={{
backgroundColor: "tomato",
color: "white",
paddig: "10px 20px",
border: 0,
borderRadius: 10,
}}
>
{text}
</button>
);
}
🎨 style 안에서의 if else
변경되는 text뿐만 아니라
style
에서도 차이를 줄 수 있다.
- 위 사진과 같이 같은 형태를 가졌지만, text뿐만 아니라 font 크기에서도 차이가 있는 것을 볼 수 있다.
function Btn({ text, big }) {
return (
<button
style={{
backgroundColor: "tomato",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
fontSize: big ? 20 : 16,
}}
>
{text}
</button>
);
}
function App() {
return (
<div>
<Btn text="Save Changes" big={true} />
<Btn text="Continue" big={false} />
</div>
);
}
📜 참고
Author And Source
이 문제에 관하여([React] component와 props의 이해), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@hye_rin/React-component와-props의-이해저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)