react设置props的默认值

一般设置props的默认值有两种方式

  1. 指定 props 的默认值, 这个方法只有浏览器编译以后才会生效
    class HandsomeBoy extends Component{
      // 设置默认值
      //defaultProps 可以为 Class 组件添加默认 props,基于 static 的写法
      static defaultProps = {
        name:'pyq'
      }
      constructor(props){
        super(props)
      }
      render(){
      return <section>{this.props.name}</section>
      }
    }
  2. 指定 props 的默认值,这个方法会一直生效
    class Age extends Component{
      
      render(){
        return <section>{this.props.name}</section>
    
      }
    }
    // 默认值的第二种,指定 props 的默认值,这个方法会一直生效
    Age.defaultProps = {
        name:18
    }

     

posted on 2020-10-12 16:21  漫思  阅读(4421)  评论(0编辑  收藏  举报

导航