React 기초(5) - Props 사용

1 minute read

Props

컴포넌트 반복 제거

Props을 알아보기 전에 컴포넌트 반복 제거에 대해 알아보자.

다음과 같이 똑같은 함수를 반복한다면 굉장히 비효율적일 것이다. 이를 위해 반복되는 함수를 컴포넌트화해서 이를 따로 놔두어 임포트해 사용한다.

import React, { useEffect, useState } from "react";

function App() {
  const [count, setCount] = useState(0);
  const [count1, setCount1] = useState(0);
  const [count2, setCount2] = useState(0);
  const increment = () => {
    setCount(count + 1);
  };

  const increment1 = () => {
    setCount1(count1 + 1);
  };

  const increment2 = () => {
    setCount1(count2 + 1);
  };
  return (
    <div className="App">
      <h1>kgw</h1>
      <button onClick={increment}>Click {count}</button>
      <button onClick={increment1}>Click {count1}</button>
      <button onClick={increment2}>Click {count2}</button>
    </div>
  );
}

export default App;

따로 컴포넌트 폴더를 만들고 그 안에 모듈을 저장하면 이를 통해 반복되거나 모듈화 해놓으면 좋은 컴포넌트를 따로 관리할 수 있다.

그리고 이를 App.js에서 임포트해와서 사용할 수 있다.

// src/components/Counter.js

import React, { useState } from "react";

function App() {
  const [count, setCount] = useState(0);
  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div className="App">
      <button onClick={increment}>Click {count}</button>
    </div>
  );
}

export default App;
import React from "react";
import Counter from './components/Counter';

function App() {
  
  return (
    <div className="App">
      <h1>kgw</h1>
      <Counter />
      <Counter />
      <Counter />
    </div>
  );
}

export default App;

Props

위처럼 다른 컴포넌트에서 불러와서 사용하는 컴포넌트를 부모 컴포넌트라고 하는데 여기에 속성처럼 값을 줄 수 있다.

import React, { useState } from "react";

function Counter(props) {
  const [count, setCount] = useState(0);
  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div className="App">
      <button onClick={increment}>Click {props.click}{count}</button>
    </div>
  );
}

export default Counter;
import React from "react";
import Counter from './components/Counter';

function App() {
  
  return (
    <div className="App">
      <h1>kgw</h1>
      <Counter click="click1"/>
    </div>
  );
}

export default App;

위와 같이 스트링만 보낼 수 있는 것이 아니라 state 또한 보낼 수 있다.

import React, { useState } from "react";
import Counter from './components/Counter';

function App() {
  const [buttonName, setButtonName] = useState('클릭');
  const clickButton = () => {
    setButtonName('click');
  };
  return (
    <div className="App">
      <h1>kgw</h1>
      <Counter click={buttonName}/>
      <button onClick={clickButton}>Click</button>
    </div>
  );
}

export default App;

Leave a comment