React.Component
와 React.PureComponent
를 기반으로 만든 컴포넌트를 말한다.state
값이 바뀌면 렌더링을 다시 한다.state
와 Life-cycle method 사용이 불가능하다.👉
hooks
의 등장으로 함수 스타일 컴포넌트도state
와 Life-cycle method 사용이 가능해졌다!
PS C:\Studying\react-class-vs-function> npx create-react-app .
npm start
App.js
import React from 'react';
import './App.css';
function App() {
return (
<div className="container">
<h1>Hello World!</h1>
<FuncComp></FuncComp>
<ClassComp></ClassComp>
</div>
);
}
// Function Component
function FuncComp() {
return (
<div className="containter">
<h2>Function style component</h2>
</div>
)
}
//Class Component
class ClassComp extends React.Component {
render() {
return (
<div className="container">
<h2>Class style component</h2>
</div>
)
}
}
export default App;
App.css
.container {
border: 5px solid red;
margin: 5px;
padding: 5px;
}
화면 출력
props
사용import React from 'react';
import './App.css';
function App() {
return (
<div className="container">
<h1>Hello World!</h1>
<FuncComp initNumber={2}></FuncComp>
<ClassComp initNumber={2}></ClassComp>
</div>
);
}
// props를 함수에 인자로 넣어주고, props.initNumber로 받아올 수 있다.
function FuncComp(props) {
return (
<div className="container">
<h2>Function style component</h2>
<p>Number : {props.initNumber}</p>
</div>
);
}
class ClassComp extends React.Component {
render() {
return (
<div className="container">
<h2>Class style component</h2>
<!-- 함수처럼 인자를 받아올 필요 없이 this.props.initNumber로 받아올 수 있다. -->
<p>Number : {this.props.initNumber}</p>
</div>
)
}
}
export default App;