Web Frontend

React Component

이타심 2022. 7. 7. 18:56
728x90
Component

# 개요

React를 사용하여 애플리케이션, 웹 페이지 인터페이스를 설계할 때, 사용자가 볼 수 있는 요소는 여러 가지 Component로 구성되어 있다. Component는 데이터가 주어지면, 해당 데이터를 통해 UI를 구성하고 api를 이용하여 component가 화면에 나타나고 사라지는 변화를 처리할 수 있다. 또한 임의의 method를 만들어 특별한 기능을 추가하는 것도 가능하다.

 

# 종류

  • Function Component
  • Class Component

 

# Function Component

component를 선언하는 방식은 크게 두 가지로 나뉜다. 하나는 Function Component이고, 다른 하나는 Class Component이다. 

import React from 'react';
import './App.css';

function App(){
  const name = 'React';
  return <div className="react">{name}</div>;
}

export default App;

위 코드는 function Component를 나타낸 것이다. 보통은 Component에서 lifecycle API와 state를 사용하기 위해 Class Component를 주로 선언하지만, 단순히 props만 전달해주는 역할이라면 Function Component 형식으로 정의할 수 있다. function component는 lifecycle 기능을 사용할 수 없지만, Hooks를 통해 비슷한 작업 처리가 가능하다.

import React, {Component} from 'react';

class App extends Component{
  render(){
    const name = 'react';
    return <div className="react">{name}</div>;
  }
}

export default App;

해당 코드는 위의 function Component를 수정하여 작성한 동일한 기능을 수행하는 Class Component이다. Class Component는 state의 기능과 lifecycle 기능을 사용할 수 있고, 임의 method 정의가 가능하다. 또한 Class Component는 render 함수를 꼭 가지고 있어야 하며, 내부에서 보여줄 JSX를 return 해야 한다.

 

또한 추가적인 차이점은 무엇이 있을까?

  • State 사용의 차이

state는 Component 내부에서 사용되며 바뀔 수 있는 값이다.

constructor(props){
    super(props);
    
    this.state = {
    	initialState = "",
    }
}

Class에서는 다음과 같이 constructor 내부에 this.state로서 초기 값 설정이 가능하고, constructor 없이 바로 설정도 가능하다. 해당 state에 새로운 값을 할당할 때는, this.setState()로서 설정할 수 있다.

 

const [initialState, setInitialState] = useState("");

Function Component는 useState 함수로서 state를 사용한다. useState로서 초기 값을 설정하고, setInitialState를 통해 새로운 값을 할당할 수 있다.

 

  • props 사용의 차이

props는 Component 속성을 설정할 때 사용하는 요소로서, state와 다르게 readonly 특성을 가진다.

Class example extends Component {
  render(){
    const {name} = this.props;
    
    return (
      <div>name = {name}</div>
    )
  }
}

 

Class Component에서는 this.props를 통해 값을 불러온다. 부모 객체에서의 키 값을 자식 props로 활용한다.

 

const example = ({name}) => {
  return(
    <div>name = {name}</div>
  )
}

Function Component는 this.props로 불러올 필요 없이 파라미터로 바로 호출이 가능하다.

728x90

'Web Frontend' 카테고리의 다른 글

React Hooks  (0) 2022.07.14
React Lifecycle method  (0) 2022.07.12
React ForEach, Map  (0) 2022.07.12
React Props, State  (2) 2022.07.06
React Checkbox 구현하기  (0) 2022.07.05