728x90
함수 컴포넌트 와 클래스 컴포넌트
- 함수 컴포넌트
- 이 함수는 데이터를 가진 하나의 "props"(props는 속성을 나타내는 데이터) 객체 인자를 받은 후 React 엘리먼트를 반환하므로 유효한 React 컴포넌트
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
- 클래스 컴포넌트
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
컴포넌트 렌더링
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Sara" />;
ReactDOM.render(
element,
document.getElementById('root')
);
- <Welcome name="Sara" /> 엘리먼트로 ReactDOM.render()를 호출
- React는 {name: 'Sara'}를 props로 하여 Welcome 컴포넌트를 호출
- Welcome 컴포넌트는 결과적으로 <h1>Hello, Sara</h1> 엘리먼트를 반환
- React DOM은 <h1>Hello, Sara </h1> 엘리먼트와 일치하도록 DOM을 효율적으로 업데이트
*주의*
- 컴포넌트의 이름은 항상 대문자로 시작
- React는 소문자로 시작하는 컴포넌트를 DOM태그로 처리
컴포넌트 합성
- 컴포넌트는 자신의 출력에 다른 컴포넌트를 참조
- React 앱에서는 버튼, 폼, 다이얼로그, 화면 등의 모든 것들이 흔히 컴포넌트로 표현
- 예를 들어 Welcome을 여러번 렌더링 하는 App 컴포넌트 제작가능
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
컴포넌트 추출
- 컴포넌트를 여려개의 작은 컴포넌트로 나눌수 있다.
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">
{formatDate(props.date)}
</div>
</div>
);
}
Avatar 추출
function Avatar(props) {
return (
<img className="Avatar"
src={props.user.avatarUrl}
alt={props.user.name}
/>
);
}
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<Avatar user={props.author} />
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
UserInfo 추출
function UserInfo(props) {
return (
<div className="UserInfo">
<Avatar user={props.user} />
<div className="UserInfo-name">
{props.user.name}
</div>
</div>
);
}
function Comment(props) {
return (
<div className="Comment">
<UserInfo user={props.author} />
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
props는 읽기 전용
- 함수 컴포넌트나 클래스 컴포넌트 모두 컴포넌트의 자체 props를 수정해서는 안됨
- "state"를 이용해서 위 규칙을 위반하지 않고 사용자 액션, 네트워크 응답 및 다른 요소에 대한 응답으로 시간에 따라 자신의 출력값을 변경 가능
728x90
'프로그래밍 > react' 카테고리의 다른 글
[react] 이벤트 처리하기 (0) | 2023.05.17 |
---|---|
[react] State (0) | 2023.05.16 |
[react] Hook (0) | 2023.05.15 |
[react] Lifecycle(생명주기) (0) | 2023.05.14 |
[react] react-router-dom (0) | 2023.05.13 |