react中的 PropTypes使用

安装

npm i prop-types

类式组件

import {
    
    Component} from 'react'
import PropTypes from "prop-types";

class Two extends Component {
    
    
   static propTypes = {
    
      // 对props进行校验
    name: PropTypes.string.isRequired,
    age: PropTypes.number
  }
  static defaultProps = {
    
     // 对props的默认值进行处理
    age: 30
  }
  constructor(props){
    
    
    super(props)
    console.log('123', props)
  }
  render () {
    
    
    return (
      <div>
        <h1>这是Two!!!</h1>
      </div>
    )
  }
}
export default Two

函数式组件

import PropTypes from "prop-types";
function Three (props) {
    
    
  console.log(props)
  return (
    <div>
      <h1>这是Three了!</h1>
    </div>
  )
}
Three.propTypes = {
    
     // 对props进行校验
  name: PropTypes.string.isRequired
}
Three.defaultProps = {
    
     // 对props的默认值进行处理
  name: '大锤'
}
export default Three

猜你喜欢

转载自blog.csdn.net/qq_46433453/article/details/127766644