본문 바로가기

React

컴포넌트 (Component)

function Child(props){
	console.log(props) // 이게 바로 props다.
	return <div>연결 성공</div>
}

1️⃣ 3.1 클래스형 컴포넌트

리액트 컴포넌트를 표현하는 두 가지 방법

✅함수형 컴포넌트( 공식 홈페이지에서는 함수형 컴포넌트 사용 권장)

// props라는 입력을 받음
// 화면에 어떻게 표현되는지를 기술하는 React 엘리먼츠를 반환(return)

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

// 훨씬 쉬운 표현을 해보면 아래와 같죠.
function App () {
	return <div>hello</div>
}

✅클래스형 컴포넌트

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

Component 보는 방법

컴포넌트(함수) 코드를 볼 때는 영역을 나누어 보기

2️⃣ 3.2 첫 컴포넌트 생성

주의!

컴포넌트를 만들 때 반드시 가장 첫 글자 대문자

[폴더]는 소문자로 시작하는 카멜케이스로 작성하고,
컴포넌트를 만드는 [파일]은 대문자로 시작하는 카멜케이스로 작성

 

import React from 'react';
function App() {
  
	// <---- 자바스크립트 영역 ---->
    const handleClick = () => {
    alert('클릭!');
  };

  return (
  /* <---- HTML/JSX 영역  ---->*/
    <div
      style={{
        height: '100vh',
        display: ' flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
      }}
    >
   <span>이것은 내가 만든 App컴포넌트 입니다</span>
      <button onClick={handleClick}>클릭!</button>
    </div>
  );
}

export default App;

 

3️⃣ 3.3 props

컴포넌트 끼리의 정보교환 방식!

  1. props는 반드시 위에서 아래 방향으로 흐른다. 즉, [부모] → [자식] 방향으로만 흐른다(단방향).
  2. props는 반드시 읽기 전용으로 취급하며, 변경하지 않는다.

props로 값 전달하기

1. 전달하기 - [주체 : 부모] : 컴포넌트 간의 정보를 교류할 때 Props를 사용

2. 받기 - [주체 : 자식] : 컴포넌트의 인자에서 props의 값을 받음

function Child(props){
	console.log(props) // 이게 바로 props다.
	return <div>연결 성공</div>
}
// src/App.js

import React from "react";

function Child(props) {
  return <div>{props.grandFatherName}</div>;
}

function Mother(props) {
  return <Child grandFatherName={props.grandFatherName} />;
}

function GrandFather() {
  const name = "이범규";
  return <Mother grandFatherName={name} />;
}

function App() {
  return <GrandFather />;
}

export default App;

🔥prop drilling : [부모] → [자식] → [그 자식] → [그 자식의 자식] 이 데이터를 받기 위해선 무려 3번이나 데이터를 내려줘야 해요. 이걸 바로 prop drilling, props가 아래로 뚫고 내려간다. 라고 함 

[ 이를 피하기 위해  ‘Redux’와 같은 데이터 상태관리 툴 사용]

export default function App() {
  return (
    <div className="App">
      <FirstComponent content="Who needs me?" />
    </div>
  );
}

function FirstComponent({ content }) {
  return (
    <div>
      <h3>I am the first component</h3>;
      <SecondComponent content={content} />|
    </div>
  );
}

function SecondComponent({ content }) {
  return (
    <div>
      <h3>I am the second component</h3>;
      <ThirdComponent content={content} />
    </div>
  );
}

function ThirdComponent({ content }) {
  return (
    <div>
      <h3>I am the third component</h3>;
      <ComponentNeedingProps content={content} />
    </div>
  );
}

function ComponentNeedingProps({ content }) {
  return <h3>{content}</h3>;
}

4️⃣ 3.4 state

State란 컴포넌트 내부에서 바뀔 수 있는 값을 의미

(왜 바뀌어야 할까?  바로 UI(엘리먼트)로의 반영을 위해)

 

State를 만들 때는 useState()를 사용 ( useState 라는 함수를 이용해서 state를 만듦)

useState 는 state를 만들어주는 리액트에서 제공하는 기능

리액트에만 존재하는 개념이자 기능입니다. 그리고 앞으로 우리는 이것을 “기능” 이라고 하지 않고 “훅” 이라고 표현

import React, { useState } from 'react';

function GrandFather() {
  const [name, setName] = useState("김할아"); // 이것이 state!
  return <Mother grandFatherName={name} />;
}

// .. 중략

✔ useState 훅을 사용하는 방식

const [ value, setValue ] = useState( 초기값 )

// 먼저 const 로 선언을 하고 [ ] 빈 배열 을 생성하고, 
// 배열의 첫번째 자리에는 이 state의 이름, 
// 그리고 두번째 자리에는 set 을 붙이고 state의 이름을 붙입니다. 
// 그리고 useState( ) 의 인자에는 이 state의 원하는 처음값 을 넣어줌

State 변경하기

state를 변경할때는 setValue(바꾸고 싶은 값) 를 사용

// src/App.js

import React, { useState } from "react";

function Child(props) {
  return (
    <div>
      <button
        onClick={() => {
          props.setName("박할아");
        }}
      >
        할아버지 이름 바꾸기
      </button>
      <div>{props.grandFatherName}</div>
    </div>
  );
}

function Mother(props) {
  return (
    <Child grandFatherName={props.grandFatherName} setName={props.setName} />
  );
}

function GrandFather() {
  const [name, setName] = useState("김할아");
  return <Mother grandFatherName={name} setName={setName} />;
}

function App() {
  return <GrandFather />;
}

export default App;

 

5️⃣ 3.5 state를 사용할 때 주의사항

 

 

6️⃣ 3.6 정리

'React' 카테고리의 다른 글

ref : DOM에 이름 달기  (0) 2024.01.05
컴포넌트 분리's 정석  (0) 2024.01.05
React : Button Modal Input Select 기본기능 구현  (1) 2024.01.05
Styled Router Redux 구현  (0) 2024.01.02
Virtual DOM, props, state  (1) 2023.12.31