함수형 컴포넌트
함수형 컴포넌트란
함수형 컴포넌트는 state가 없는 컴포넌트(Stateless Functional Component)를 말한다. 줄여서 SFC 라고도 부른다. 함수형 컴포넌트는 state를 포함하지 않으며 데이터를 받아 출력할 컴포넌트를 반환한다.
함수형 컴포넌트의 구조
함수형 컴포넌트는 함수와 동일한 구조를 가지고 있어서 함수의 구조를 떠올리면 쉽다. 즉, 입력받은 프로퍼티와 컨텍스트를 이용하여 화면을 출력하는 것이다.
함수형 컴포넌트 예제
import React from "react";
import PropTypes from "prop-types";
function SFC(props, context) { //properties와 context를 인자로 받음. (stateless라 state는 없음.)
const { somePropValue } = props;
//컴포넌트의 구성요소 중 하나인 context 는 이후에 다룰 예정
const { someContextValue } = context;
return <h1>Hello, {somePropValue}</h1>;
}
SFC.propTypes = { somePropValue: PropTypes.any }; //Props 자료형 정의
SFC.defaultProps = { somePropValue: "default value" }; //기본값 설정
export default SFC;
함수형 컴포넌트에 state 만들기
앞서 함수형 컴포넌트는 state가 없는 컴포넌트라고 배웠는데 이런 함수형 컴포넌트에 state를 쓸 수 있게 하는 것이 react 라이브러리의 useState() 함수이다. useState() 에는 state 변수와 변수를 수정하는 함수가 들어있다. 이를 배열 형식으로 구조분해하여 " const [ <변수명>, set<변수명> ] = useState( <초깃값> ); " 로 쓸 수 있다. (관례적으로 변수를 수정하는 함수는 set+ 변수명의 이름으로 쓰는데 변수명의 첫글자를 대문자로 작성한다. )
* 자세한 내용은 뒤에서 더 배우도록 하겠다. (지금은 이런 것이 있구나 느낌으로 아시면 됩니다. :) )
import React, { useState } from "react";
function SFC(props) {
const [contents, setContents] = useState(props.somePropValue);
return (
<div>
<h1>Hello, {contents}</h1>
<button onClick={() => setContents("[ new Contents ]")}>버튼</button>
</div>
);
}
export default SFC;
클래스형 컴포넌트에서 함수형 컴포넌트로 변환
App.js
//App.js
import React, { Component } from "react";
import MyComponents from "./MyComponents";
class App extends Component {
render() {
return (
<div>
<MyComponents name="Y씨" />
</div>
);
}
}
export default App;
MyComponents.js (클래스형 컴포넌트)
import React, { Component } from "react";
export default class MyComponents extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
name: props.name,
};
this.onClickHandler = this.onClickHandler.bind(this);
}
onClickHandler(e) {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Hello, {this.state.name}</p>
<button onClick={this.onClickHandler}>
Click Count {this.state.count}
</button>
</div>
);
}
}
MyComponents.js (함수형 컴포넌트) ⭐
import React, { useState } from "react";
function MyComponents(props) {
const [count, setCount] = useState(0);
const [name, setName] = useState(props.name);
return (
<div>
<p>Hello, {name}</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click count {count}
</button>
</div>
);
}
export default MyComponents;
먼저 함수형 컴포넌트에서는 this.state는 쓰지 않으므로 이것들과 this.setState() 함수들은 모두 없애주면 된다. 이 대신 함수형 컴포넌트에서는 useState() 함수를 사용한다. state의 변수명과 set+변수명의 변화 함수를 구조 분해로 묶어준다. 그리고 constructor에서 초기화 했던 초깃값을 useState의 인자로 전달하면 된다. 또한 state 값을 바꾸는 함수들은 따로 만들어도 되지만 useState의 변화함수에서 익명함수를 통해 정의해주는 것이 좋다.
그 다음으로 Props의 경우 this.props로 구조분해를 했던 클래스형 컴포넌트 형식과 다르게 함수형 컴포넌트에서는 컴포넌트의 인자로 전달하면 된다. 예를 들면 MyComponents( props ) 처럼 컴포넌트의 인자로 프로퍼티를 전달하면 된다.
또한 함수형 컴포넌트는 render() 함수가 없다. render() 함수에 있었던 return문은 그대로 사용하고 그 위에 있던 구문들은 그대로 return문 위에 올려두면 된다.
마지막으로 함수형 컴포넌트에는 this 가 없다. 따라서 this.props, this.state 등으로 접근할 필요 없이 state 변수의 경우 그냥 그 이름으로 접근하고 props는 props.변수명 혹은 props를 구조분해 하여 변수에 담고 접근하면 된다.
'Javascript > React 지식' 카테고리의 다른 글
[React] 클래스형 컴포넌트 (0) | 2023.04.23 |
---|---|
[React] 컴포넌트의 생명주기로 본 NewCounter 예제 (0) | 2023.04.23 |
[React] 컴포넌트의 생명주기 (2) | 2023.04.23 |
[React] 리액트 컴포넌트 : State (0) | 2023.04.23 |
[React] 리액트 컴포넌트 : Property (0) | 2023.04.22 |