웹개발/FrontEnd

[React] 리액트 시작하기(2) - Components & Props

토킹포테토 2023. 5. 30. 10:56
728x90

* 컴포넌트란?

: React의 핵심 개념으로 사용자 인터페이스(UI)를 구축하는 기반

 

 

1. 함수 컴포넌트

* props = 속성을 나타내는 데이터

function Welcome(props){
	return <h1>Hello , {props.name}</h1>;
}

객체 인자(props)를 받은 후 React 엘리먼트에 반환하므로 React 컴포넌트이며 

JavaScript 함수이기 때문에 "함수 컴포넌트"라고 호칭한다.

 

2. 클래스 컴포넌트

Class Welcome extends React.Component{
	render(){
    	return <h1>Hello, {this.props.name}</h1>;
        }
}

 

* 컴포넌트 렌더링

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="talkingPotato" />;
root.render(element);


// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

1. <Welcome name="talkingPotao"/> 엘리먼트로 root.render() 호출.

2. React는 name=talkingPotato 를 props로 Welcome 컴포넌트를 호출.

3. Welcome 컴포넌트는 <h1> Hello, talkingPotato </h1> 엘리먼트 반환.

 

* 컴포넌트의 이름은 항상 "대문자"로 시작!

 

결과