一般設置props的默認值有兩種方式
- 指定 props 的默認值, 這個方法只有瀏覽器編譯以后才會生效
class HandsomeBoy extends Component{ // 設置默認值 //defaultProps 可以為 Class 組件添加默認 props,基於 static 的寫法 static defaultProps = { name:'pyq' } constructor(props){ super(props) } render(){ return <section>{this.props.name}</section> } }
- 指定 props 的默認值,這個方法會一直生效
class Age extends Component{ render(){ return <section>{this.props.name}</section> } } // 默認值的第二種,指定 props 的默認值,這個方法會一直生效 Age.defaultProps = { name:18 }