3.2 Props

hey hey·2021년 12월 9일
0

리액트 배우기

목록 보기
4/26
post-thumbnail

Props

  • properties; 컴포넌트 속성을 설정할 때 사용하는 요소
  • props 값은 해당 컴포넌트를 불러 사용하는 부모 컴포넌트에서 설정 <Mycomponent name="heyhey"/> → 부모 컴포넌트에서 넘겨주기
    const MyComponent = **props** =>{
    	return <div>하이 {props.name}이야</div>}

부모 컴포넌트에서 태그사이에 적었으면?

props.children 을 사용해서 사용가능

<Mycomponent>여기적히는값</Mycomponent>

const Mycomponent = (props) =>{
  return <div> **{props.children}**</div>
}

기본값 부여

Mycomponent.defaultProps={
  name:'기본값'
}

props 편하게 사용하기(등록)

const Mycomponent = (props) =>{
  const {name,children} =props;
	return ..
}

애초에 props 대신 적기

const Mycomponent = ({name,children}) =>{
	return ..
}

propTypes

  • 컴포넌트의 필수 props나 props의 타입을 지정할 때 PropTypes를 사용한다.
    import PropTypes from 'prop-types'
    (..)
    Mycomponent.propTypes ={
    	name:PropTypes.string
    }
    → name에 string이 아닌 int가 적히면 console에 err 출력
  • **isRequired** 를 사용해 필수 propTypes 설정
    Mycomponent.propTypes ={
    	name:PropTypes.string,
      num:PropTypes.number.isRequired
    }
    isRequired 를 적어주면, num을 설정 안하면 err 출력 숫자 넘길때 num={2} 이런 형태로 넘겨야 한다 number 대신 array, func, object, oneOf(['dog','cat']) .. 가능 더 자세한 propTypes는 여기에서 확인

클래스형 컴포넌트에서 props 사용하기

  • this.props로 불러오기
  • 함수형태 : const {name,num,children} = props;
  • 클래스형 : const {name,num,children} = this.props
import React,{Component} from 'react'

class Mycomponent extends Component{
  render(){
    const {name,num,children} = this.props
    return(
      <div>{name}{num}{children}</div>
    )
  }
}
profile
FE - devp

0개의 댓글