React props 기초

권슬기·2023년 6월 5일
0

react

목록 보기
5/17
//app.js

import React from 'react';
import Counter from './Counter';

function App() {


  return (
    <div>
      <Counter a={1} initialvalue={5}/>
    </div>
  );
}

export default App;

//counter.js
import React, {useState} from 'react';

const Counter = (props) => {
    const [count, setCount] = useState(props.initialvalue);

    const onIncrease = () => {
        setCount(count + 1);
    }

    const onDecrease = () => {
        setCount(count - 1);
    }

    return (
        <div>
            <h2>{count}</h2>
            <button onClick={onIncrease}>+</button>
            <button onClick={onDecrease}>-</button>
        </div>
    )
}

export default Counter;

요렇게 하면 app.js에서 보낸 props가 전달되어 counter.js의 초기값이 5가 되어 출력 된다.

//counter.js
import React, {useState} from 'react';

const Counter = ({initialvalue}) => {
    const [count, setCount] = useState(initialvalue);

    const onIncrease = () => {
        setCount(count + 1);
    }

    const onDecrease = () => {
        setCount(count - 1);
    }

    return (
        <div>
            <h2>{count}</h2>
            <button onClick={onIncrease}>+</button>
            <button onClick={onDecrease}>-</button>
        </div>
    )
}

export default Counter;

이렇게 비구조화로 가져와도 동일한 값이 나온다.


혹시 Props로 전달한 값이 많다면 하나씩 써주기 벅차다. 그러면 부모 컴포넌트에서 축약하여 자식 컴포넌트에 '펼쳐서 전달하는 스프레드 형태'로 전달이 가능하다.

//app.js

import React from 'react';
import Myheader from './Myheader';
import Counter from './Counter';

function App() {

  const counterProps = {
    a : 1,
    b : 2,
    c : 3,
    d : 4,
    e : 5,
  }

  return (
    <div>
      <Counter {...counterProps}/>
    </div>
  );
}

export default App;


//counter.js
import React, {useState} from 'react';

const Counter = ({e}) => {
    const [count, setCount] = useState(e);

    const onIncrease = () => {
        setCount(count + 1);
    }

    const onDecrease = () => {
        setCount(count - 1);
    }

    return (
        <div>
            <h2>{count}</h2>
            <button onClick={onIncrease}>+</button>
            <button onClick={onDecrease}>-</button>
        </div>
    )
}

export default Counter;

이렇게 주고 받을 수 있다.

본인이 바뀔 때, 부모가 리렌더 될 때, 자식이 바뀔 때 모두 리렌더 된다.

profile
병아리 프론트엔드 개발자

0개의 댓글