< class 사용하기>
- 기존 ES5 자바 스크립트에서는 객체를 구현하기 위해 prototype을 사용함
객체는 상속을 통해 코드를 재사용할 수 있게 해줌
ES6에서 등장한 class는 prototype과 같은 개념인데 쉽게 읽고 표현하기 위해 고안된 문법이다
- R012_ClassPrototype.js
import React, {Component} from 'react';
class R012_ClassPrototype extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
//ES5 prototype
var ExamCountFunc = (function() {
function ExamCount(num) {
this.number = num;
}
ExamCount.prototype.showNum = function() {
console.log('1. react_' + this.number);
};
return ExamCount;
}());
var cnt = new ExamCountFunc('200');
cnt.showNum();
//ES6 class
class ExamCountClass {
constructor(num2) {
this.number2 = num2;
}
showNum() {
console.log(`2. react_${this.number2}`);
}
}
var cnt2 = new ExamCountClass('2hundred');
cnt2.showNum();
}
render() {
return (
<h2>[THIS IS ClassPrototype]</h2>
)
}
}
export default R012_ClassPrototype;
- App.js
import React from 'react';
import './App.css';
//App.css가 App.js 보다 더 한 단계 상위 폴더에 있다면
//'./..App.css'
import ClassPrototype from './R012_ClassPrototype.js';
function App() {
return (
<div>
<h1>Start React 200!</h1>
<p>css 적용하기</p>
<ClassPrototype/>
</div>
);
}
export default App;
결과

'REACT' 카테고리의 다른 글
| REACT_ForEach (0) | 2024.09.20 |
|---|---|
| REACT_화살표 함수(Arrow Function) (0) | 2024.09.20 |
| REACT_ 전개 연산자 (0) | 2024.09.20 |
| REACT_ 자식 Component에 node 전달하기 (0) | 2024.09.20 |
| REACT_props 객체형 (0) | 2024.09.20 |