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
    }
漫思
原文地址:https://www.cnblogs.com/sexintercourse/p/13803564.html