컴포넌트
컴포넌트 생성하는 방법
1. scr 디렉터리 내부에 -(이름 자유).js 파일 생성
2. 컴포넌트 초기 코드 작성
import React,{Component} from 'react';
class Content extends Component{
render(){
return(
<article>
<h2>{this.props.title}</h2>
{this.props.sub}
</article>
);
}
}
export default Content;
모듈 내보내기 export default MyComponent;
모듈 불러오기 import
props
props는 컴포넌트 속성을 설정할 때 사용하는 요소이다,.
props 같은 해당 컴포넌트를 불러와 사용하는 부모 컴포넌트(현 상황에서는 App 컴포넌트가 부모 텀포넌트)에서만 설정할 수 있다.
MYComponent.js
import React,{Component} from 'react';
class MyContent extends Component{
render(){
return(
<article>
<h2>{this.props.title}</h2>
{this.props.sub}
</article>
);
}
}
export default Content;
해당 컴포넌트에서 title과 sub라는 props를 렌더링하여 설정해 봅시다. props를 렌더링할 때는 JSX 내부에서 { }감싸 주면 된다.
props에 접근할 때는 이렇게 this 키워드를 사용하여 접근합니다.
App.js
import React,{Component} from 'react';
import MyComponent from "./MyComponent/"
class App extends Component{
render(){
return(
<div className='App'>
<MyComponent title=" "
sub=" " ></MyComponentt>
);
}
}
}
export defalut App;
props 기본 값 설정: defaultProps
MYComponent.js
import React, {Component} from 'react';
class MyContent extends Component{
static defaultProps={
name: '기본 이름'
}
render(){
return(
<article>
<h2>{this.props.title}</h2>
{this.props.sub}
</article>
);
}
}
export default Content;
props 검증: propTypes
컴포넌트의 필수 props를 지정하거나 타입을 지정할 때는 propTypes를 사용한다.
컴포넌트의 propTypes를 지정하는 방법은 defaultProps를 설정하는 것과 비슷하다.
propTypes를 사용하려면 우선 코드 위쪽에 propTypes를 불러와야 한다.
state
props는 부모 컴포넌트가 설정하며, 컴포넌트 자신은 해당 props를 읽기 전용으로만 사용할 수 있다.
컴포넌트 내부에서 읽고 또 업데이트할 수 있는 값을 사용하려면 state를 써야 한다.
이것은 언제나 기본 값을 미리 설정해야 사용할 수 있으며, this.setState()메서드로만 값을 업데이트해야 한다.
정리
props와 state는 둘 다 컴포넌트에서 사용하거나 렌더링할 데이터들을 담고 있으므로 비슷해 보일 수도 있지만, 역할은 매우 다르다.
props는 부모 컴포넌트가 설정하고 state는 컴포넌트 자체적으로 지닌 값으로 컴포넌트 내부에서 값을 업데이트 한다.
props를 사용한다고 해서 값이 무조건 고정적인 것은 아니다. 부모 컴포넌트의 state를 자식 컴포넌트의 state를 자식 컴포넌트의
props로 전달하고, 자식 컴포넌트에서 특정 이벤트가 발생할 때 부모 컴포넌트의 메서드를 호출하면 props도 유동적으로 사용할 수 있다.
'개발 노트 > React' 카테고리의 다른 글
[React] 리액트 시작하기, JSX 사용법(소플의 처음만난 리액트) (0) | 2023.09.05 |
---|---|
리액트를 다루는 기술 요약- 이벤트 핸들링 (0) | 2022.02.25 |
리액트를 다루는 기술 요약- 리액트, JSX 정의 (0) | 2022.02.22 |