frontend (React) 개발
(React) Props
꼰대코더
2023. 11. 23. 02:36
component 간에 데이터를 전달할 때 사용
데이터를 받는 방법
1. 받는 함수의 파라미터에 { 변수명1, 변수명2, ... } 을 명시
// 호출측 <Message greet="Welcome" who="John" /> // 받는측 function Message( { greet, who } ) { return <div>{greet}, {who}!</div>; } |
2. 받는 함수의 파라미터로 props 를 선언
// 호출측 <Hello who="John"> // 받는측 function Hello(props) { return <div>Hello, {props.who}!</div>; } |
3. 받는측이 클래스의 경우
// 호출측 // Render <HelloAsClass who="John" /> // 받는측 import { Component } from 'react'; class HelloAsClass extends Component { render() { return <div>Hello, {this.props.who}!</div>; } } |
4. Props value의 타입
- string : prop="My String Value"
- 변수 혹은 변수의 조합: prop={`My String Value ${myVariable}`}
- 숫자 (int, double, float...) : prop={55}
- boolean : prop={true}
- dictionary : prop={{ property: 'Value' }}
- Array : prop={['Item 1', 'Item 2']}
- JSX : prop={<Message who="Joker" />}
5. children
<component> 여기 부분을 children 으로 전달 </component>
// 호출측 <Parent> <span>I'm a child!</span> </Parent> function Parent({ children }) { console.log(children); // logs <span>I'm a child!</span> return <div>{children}</div>; } |