<aside> 💡 컴포넌트에 데이터를 전달하는 방

</aside>

홀수 짝수 체크

Container (부모 자식 요소)

App.js

부모컴포넌트에 선언되어있는 자식 컴포넌트에 이름을 달고 값을 등록할 수 있다. (Props)

import React from 'react';
// import './App.css';

import MyHeader from './MyHeader';
import Counter from './Counter';

function App() {
  const number = 5;

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

export default App;

하지만 저렇게 하나하나 전달하지 말고 spread 연산자 이용해서 하자

import React from 'react';
// import './App.css';

import MyHeader from './MyHeader';
import Counter from './Counter';

function App() {
  const number = 5;

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

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

export default App;

Counter.js

이렇게 자식 컴포넌트에서 매개변수의 인자로 받으면 객체로 받게 된다.

import React, {useState} from 'react';

const Counter = (**props**) => {

    console.log(props)
    //const [count, setCount] = useState(0);
		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;

Untitled

하지만 비구조화 할당 방식을 이용해 이름에 대해서 해당 값만 꺼낼 수 있으며 부모에서 해당 initialValue를 선언하지 않았을 땐 undefined가 된다.

import React, {useState} from 'react';

const Counter = ({ initialValue }) => {

   
    //const [count, setCount] = useState(0);
		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>
    );
};

Counter.defaultProps={
	initialValue:0
}

export default Counter;