Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Generic
- animation
- MINUS
- mongoose
- lifecycle
- Service
- function
- docker-compose
- CLASS
- AWS
- LiveData
- collection
- ConstraintLayout
- Swift
- Filter
- map
- list
- vuex
- elementAt
- 생명주기
- react native
- enum
- recyclerview
- class component
- union
- Kotlin
- Interface
- ReactNative
- Foreign Key
- docker
Archives
- Today
- Total
개발 일기
Props 본문
프로퍼티는 상위 컴포넌트가 하위 컴포넌트에게 값을 전달할 때 사용합니다.
아래와 같이 속성형태로 값을 전달할수 있는것을 프로퍼티라고 합니다.
function App() {
return (
<div className="App">
<Main name="111"/>
</div>
);
}
이제 위와 같이 name에 해당하는 값을 아래와 같이 this.props.name으로 값을 참조할수가 있습니다.
import React from 'react'
class MainComponent extends React.Component {
render() {
return (
<div className="main">
{this.props.name}
</div>
)
}
}
export default MainComponent
기억해야하는 내용은 위와같이 상위 컴포넌트에서 하위 컴포넌트로 전달되는 형식입니다.
프로퍼티에서는 다양한 자료형을 모두 사용할수가 있습니다.
위와 같이 선언을 안하고 사용이 가능하지만 아래와 같이 미리 자료형을 선언을 하고 진행을 함으로써 버그를 예방하실수가 있습니다.
import React from 'react'
import PropTypes from 'prop-types'
class MainComponent extends React.Component {
render() {
return (
<div className="main">
{this.props.name}
</div>
)
}
}
MainComponent.propTypes = {
name : PropTypes.string
}
export default MainComponent
선언을 하실 때 리액트에서 제공하는 prop-types를 이용해서 만들수가 있습니다.
특이점은 bool 형 일때에는 프로퍼티 이름만 선언해도 true 없으면 false로 진행이 됩니다.
또한 프로퍼티로 객체를 받고 싶은 경우에는 아래와같이 PropTypes.shape를 사용하여 정의를 할수가 있습니다.
import './App.css';
import Main from './Main.jsx'
function App() {
return (
<Main obj={{
name : "test",
age : 1,
number : ["111" , "222"],
requireAt : "requireAt"
}}/>
);
}
export default App;
import React from 'react'
import PropTypes from 'prop-types'
class MainComponent extends React.Component {
render() {
const {
obj
} = this.props;
return (
<div className="main">
{JSON.stringify(obj)}
</div>
)
}
}
MainComponent.propTypes = {
obj : PropTypes.shape({
name : PropTypes.string,
age : PropTypes.number,
number : PropTypes.arrayOf(PropTypes.string),
requireAt : PropTypes.string.isRequired
})
}
export default MainComponent
위에서 특이점은 isRequired을 통해서 필수 프로퍼티를 지정할수가 있습니다.
기본값 지정하기
기본값을 지정하고 싶다면 아래와 같이 defaultProps을 통해서 이용이 가능합니다.
MainComponent.defaultProps = {
obj : {
name : "name",
age : 111,
number : ["111", "222"],
requireAt : "11111"
}
}
또한 자식 노드를 확인하고 싶을 경우에는 this.props.children을 통해서 확인하실수가 있습니다.
'Client > react' 카테고리의 다른 글
| 하이어오더 컴포넌트 (HOC) (0) | 2020.11.12 |
|---|---|
| Ref (0) | 2020.11.10 |
| Component , PureComponent (0) | 2020.11.10 |
| 생명주기 (0) | 2020.11.10 |
| State (0) | 2020.11.10 |
Comments