컴포넌트를 이용하여 UI를 재사용 가능한 여러 조각을 나눔.
JavaScript 함수와 유사하다!
props를 통한 입력을 받고 화면에 어떻게 표시하는 지를 기술하는 React element를 반환하는 것
function Welcome(props) {//사용자 정의 컴포넌트
return <h1> Hello, {props.name} </h1>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
//사용자 정의 컴포넌트 Welcome을 이용한 엘리먼트 정의
const element = <Welcome name="Sara" />;
root.render(element);
컴포넌트 간 합성
function Hello(props) {//컴포넌트1
return <h1>Hello, {props.name}</h1>;
}
//횟수를 인자값으로 받아 그 횟수만큼 컴포넌트1을 호출
function ManyHello(props) {//컴포넌트2
const id = ["주영", "지영", "주연"]
//for문 사용을 원할 경우 미리 함수로 완성 후 함수를 return 하자!
const rendering = ()=>{
const result = [];
for (let i = 0; i < props.num; i++) {
result.push(<Hello name={id[i]} />);
}
return result;
}
return (
<div>{rendering()}</div>
)
}
//최종 element 렌더링하는 부분
const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <ManyHello num={2}/>;
root.render(element);
원본 코드
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{props.date}
</div>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'))
const element =
<Comment
date={"20240214"}
author={{ avatarUrl: 'https://url.kr/1n6qzx', name: "잔망루피" }}
text={"루피text"}/>;
root.render(element);
컴포넌트 분해 코드
function Author(props){
return (
<div className="UserInfo">
<img className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
)
}
function Text(props){
return (
<div classNAme="Comment-text">
{props.text}
</div>
)
}
function Date(props) {
return (
<div className="Comment-date">
{props.date}
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'))
const element =
<div className="Comment">
<Author author={{ avatarUrl: 'https://url.kr/1n6qzx', name: "잔망루피" }}/>
<Text text={"루피text"}/>
<Date date={"20240214"}/>
</div>;
root.render(element);