클래스형
클래스형 컴포넌트에서 생성자를 작성할 때 반드시 props를 받고,
super를 통해서 부모컴포넌트에 연결해야 한다.
- state는 생성자 안에서 초기화한다.
- state의 접근은 this.state를 이용해서 접근한다.
- this.state={객체}. state는 반드시 객체모형 이어야 한다.
- 값을 변경할 땐 setState 내장함수 사용.
App.js
{/* 클래스형 props */}
<MyComponent3 name={"강감찬"}/>
MyComponent3
import { Component } from "react";
class MyComponent3 extends Component{
/*
state는 생성자 안에서 초기화를 합니다.
state의 접근은 this.state를 이용해서 접근합니다.
state는 반드시 객체모형이어야 합니다.
*/
//클래스형에서는 생성자를 작성할 때 반드시 props를 받고, super를 통해서 부모컴포넌트에 연결해야 합니다.
constructor(props){
super(props);
this.state={
a:1,
b:props.name//부모로부터 전달받은 name
}
}
//클래스형 컴포넌트가 제공해주는 render함수 안에서 return문을 작성
render(){
//let {name} = this.props;//props
//console.log(name);
return(
<>
<div>나의 클래스형 컴포넌트</div>
state 값 {this.state.a}<br/>
state 값 {this.state.b}<br/>
</>
)
}
}
export default MyComponent3;
'React' 카테고리의 다른 글
230116 React Event핸들링 실습 (0) | 2023.01.16 |
---|---|
230116 React Event 핸들링 (0) | 2023.01.16 |
230116 React State (0) | 2023.01.16 |
230116 React 컴포넌트 합성 (0) | 2023.01.16 |
230113 React 컴포넌트(Components), Props (0) | 2023.01.13 |