React 2가지의 버튼

줍줍·2023년 5월 16일
0

React

목록 보기
3/3

버튼을 2가지로 만드는 방법이 신기했다.

하나는 전역변수처럼 같이 count가 올라가고

하나는 지역변수처럼 다른 것으로 여겨진다.

전역변수처럼


import { useState } from 'react';

export default function MyApp() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <h1>Counters that update together</h1>
      <MyButton count={count} onClick={handleClick} />
      <MyButton count={count} onClick={handleClick} />
    </div>
  );
}

function MyButton({ count, onClick }) {
  return (
    <button onClick={onClick}>
      Clicked {count} times
    </button>
  );
}

MyButton이라는 함수를 <MyButton />으로 사용한다.(이게 객체라서 가능한 것인가?)
<img src=''>를 넣는 것처럼 <MyButton count={count} onClick={handleClick} />이 가능하다.
count와 setCount의 경우 export default를 하는 MyApp()에 있기 때문에 전역변수처럼 사용된다. 그래서 값을 올리면 동시에 같이 올라간다.

지역변수처럼


import { useState } from 'react';

export default function MyApp() {
  return (
    <div>
      <h1>Counters that update separately</h1>
      <MyButton />
      <MyButton />
    </div>
  );
}

function MyButton() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <button onClick={handleClick}>
      Clicked {count} times
    </button>
  );
}

여기서도 MyButton이라는 함수를 <MyButton />으로 사용한다.
하지만, MyButton 함수를 호출?(이 표현이 맞는지 모르겠다)하기 때문에 값이 다르게 설정된다.

Typescript에서 사용하기 위해서는,,


function MyButton({count, onClick}: {count: number; onClick: any}) {
  return <button onClick={onClick}>Clicked {count}</button>
}

위와 같이 type을 명시해줘야 한다.

공식문서를 읽어보는 중이다! https://react.dev/learn

profile
쉽게 설명하지 못하면 이해 못한 것

0개의 댓글