[React.js] 기초 - class로 component 만들기 (구문법)
2021. 4. 19. 14:41ㆍFront-end Study/React.js
Latest update : 2021.04.19 - 수정 완료
훨씬 쉬운 function형 component 바로가기
2021.04.16 - [Front-end Study/React.js] - [React.js] CRA 기초 - 설치/state/Component/props
React.js 구문법
(신문법 구문법 둘 다 알고 있어야 합니다.)
<React.js 설치>
- Node.js 설치 (nodejs.org/ko/download/)
- (CRA) npx create-react-app 프로젝트명 or yarn create react-app 프로젝트명 -> npm start
npx create-react-app 프로젝트명
(or)
yarn create react-app 프로젝트명
(and)
npm start
<Class 문법>
1. 기본
class 예시
import React, { Component } from 'react';
class Sample extends Component {
constructor(){ // constructor 함수부 생략가능
super();
}
render(){
return ( // ( 내용 ) 은 의미가 없습니다. (( 내용 )) 이렇게 들어가도 됩니다.
<div>
</div>
)
}
}
2. state
import React, { Component } from 'react';
class Sample extends Component {
constructor(){
super();
this.state = {
sample : 'sample',
sample2 : 'sample2'
}
}
render(){
return (
<div>
<p>{ this.state.sample }</p>
<button onClick={ ()=>{
this.setState( {sample2 : 'sample2수정'} );
} }>sample2 변경</button>
</div>
)
}
}
3. 함수 생성
bind(this) 사용 예시
import React, { Component } from 'react';
class Sample extends Component {
constructor(){
super();
this.state = {
sample : 'sample',
sample2 : 'sample2'
}
}
changeSample2(){
this.setState( sample2 : 'sample2 수정함수사용' )
}
render(){
return (
<div>
<p>{ this.state.sample }</p>
<button onClick={ this.changeSample2.bind(this) }>sample2 변경</button>
</div>
)
}
}
ArrowFunction 사용 예시
import React, { Component } from 'react';
class Sample extends Component {
constructor(){
super();
this.state = {
sample : 'sample',
sample2 : 'sample2'
}
}
changeSample2 = () => {
this.setState( sample2 : 'sample2 수정함수사용' )
}
render(){
return (
<div>
<p>{ this.state.sample }</p>
<button onClick={ this.changeSample2 }>sample2 변경</button>
</div>
)
}
}
'Front-end Study > React.js' 카테고리의 다른 글
[React.js] CRA 기초 - input/입력값받기/이벤트핸들러 (0) | 2021.04.19 |
---|---|
[React.js] Bootstrap 활용 - 설치/Component/Grid (0) | 2021.04.16 |
[React.js] CRA 기초 - 설치/state/Component/props (0) | 2021.04.16 |