이번에는 이전 포스트에서 사용했던 간단한 예제에 props 를 추가하여 설명해보고자 한다. 우선, props 에 대해 간략하게 짚고 넘어가야 할 거 같다.
✨ props 란?
부모 컴포넌트에서 자식 컴포넌트로 전달되는 값. 컴포넌트 간 데이터를 전달할 때 사용하는 방법으로, props 를 통해 상태가 값들을 자식 컴포넌트에서 쉽게 접근이 가능하다.
props는 properties(속성) 의 줄임말이다. 우리가 어떠한 값을 컴포넌트에게 전달해줘야 할 때 props를 사용하게 되는데, 이는 단반향 데이터 흐름을 갖고 있는 리액트의 특성을 잘 보여주는 듯 하다.
한가지 더 특징이 있다면 props는 수정할 수 없다는 것인데 이는 자식 컴포넌트 입장에선 읽기 전용인 데이터이기 때문이다.
아래는 props 를 사용한 예제이다. 파일이 여러개이니 하나씩 나누어 설명하겠다.
전체코드 및 설명
Hyunmer4.js
import styles from "./Hyunmer.module.css";
import Hyunmer3 from "./Hyunmer3";
const Hyunmer4 = () => {
return (
<div className={styles.title_container}>
<h3>Props: properties</h3>
<Hyunmer3 age={10} />
<Hyunmer3 age={20} />
<Hyunmer3 age={30} />
</div>
);
};
export default Hyunmer4;
Hyunmer3 에 age
라는 props
를 전달.
각 컴포넌트에 10, 20, 30 이라는 나이를 받을 것이다.
Hyunmer3.js
import styles from "./Hyunmer.module.css";
import { useState } from "react";
import Username from "./UserName";
const Hyunmer3 = (props) => {
console.log(props);
const [name, setName] = useState("Jane");
const [age, setAge] = useState(props.age);
const msg = age > 19 ? "성인입니다." : "미성년자입니다.";
function changeName() {
setName(name === "Jane" ? "Dylan" : "Jane");
}
function changeAge() {
setAge(age + 1);
}
return (
<div className={styles.title_container}>
<h3>State, useState</h3>
<p id="name">
{name} ({age}세 : {msg})
</p>
<Username name={name} />
<button
onClick={() => { changeName(); changeAge();}}>
Change!
</button>
</div>
);
};
export default Hyunmer3;
props
로부터 받은 age
와 내부에서 관리하는 name
상태를 관리.
버튼을 클릭하면 이름과 나이가 변경될 것이다.
Username.js
function Username({ name }) {
return <p>Hello, {name}</p>;
}
export default Username;
부모 컴포넌트인 Hyunmer3 에서 전달받은 name
을 화면에 표시해주는 단순 컴포넌트.