✍ Counter 만들어주기
파일 : Counter.js
import React, {useState} from "react";
// useState는 react의 메소드이기 때문에 따로 import 해줘야함
const Counter = () =>{
const [count, setCount] = useState(0);
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
import React from 'react';
import Counter from './Counter';
// import './App.css';
import MyHeader from './MyHeader';
function App() {
const counterProps = {
a:1,
b:2,
c:3,
initialValue:6,
}
return (
<div>
<MyHeader/>
<Counter {...counterProps}/>
// Counter 컴포넌트에 spread 연산자로 Props 전달
</div>
);
}
export default App;
파일 : Counter.js
const Counter = ({initialValue}) =>{
// 객체의 비구조화 할당
// { initialValue } = counterProps
// counterProps 객체에서 key가 initialValue인 속성의 값을 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>
)
}
✍ 에러 핸들링 : App 컴포넌트에서 Counter 컴포넌트에게 전해주는
counterProps
객체에initialValue
속성이 없을 때 기본값 설정하기파일 : Counter.js
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> ) } Counter.defaultProps={ initialValue: 0, }
defaultProps
기능을 사용하면 전달받지 못한 props의 기본값을 설정해서 에러를 방지할 수 있음
✍ props로 자식 컴포넌트에게 동적인 데이터 전달하기
동적인 데이터 대표) state
파일: Counter.js
import React, {useState} from "react";
import OddEvenResult from "./OddEvenResult";
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>
<OddEvenResult count={count}/>
//OddEvenResult 컴포넌트에 count 값을 props로 전달해줌
</div>
)
}
파일: OddEvenResult.js
const OddEvenResult = ({count}) => {
// Counter.js의 count값을 props로 받아오기
return <>{count % 2 === 0? '짝수' : '홀수'}</>
}
export default OddEvenResult;
count
값)에 따라 각각 다른 결과를 렌더하는 컴포넌트📌 컴포넌트가 rerender 되는 경우
파일: OddEvenResult.js
const OddEvenResult = ({count}) => { console.log('RENDER!'); return <>{10 % 2 === 0? '짝수' : '홀수'}</> // 리턴값이 변하지 않는 자식 컴포넌트 } export default OddEvenResult;
- 본인이 관리하는 state가 바뀔때마다 rerender
- 나에게 내려오는 props가 바뀔때마다 rerender
- 내 부모가 rerender되면 나도 rerender
✍ props로 다른 컴포넌트 전달하기
여백을 주는 컴포넌트를 전달해보자
파일: Container.js
const Container = ({children}) =>{
return <div style={{margin:20, padding:20, border:'1px solid grey'}}>
{children}
</div>
}
export default Container;
파일: App.js
function App() {
const counterProps = {
initialValue: 0,
}
return (
<Container>
<div>
<MyHeader/>
<Counter {...counterProps}/>
</div>
</Container>
); // Container 컴포넌트로 나머지 요소들을 감싸주기
}
children
이라는 prop으로 전달됨children
을 console에 출력해보면 react.element
출력https://inf.run/qAuJ
한입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지 by 이정환 Winterlood