defaultProps
的作用:
defaultProps
可以为Class
组件添加默认props
- 这一般用于
props
未赋值,但又不能为null
的情况
添加 defaultProps
的两种方法
在类中声明静态属性
static defaultProps
,这种方法只有浏览器编译以后才会生效。1
2
3
4
5
6
7
8
9static defaultProps = {
age: 18
}
render(){
return(
<h1>Hello, {this.props.name}. and my age is {this.props.age}</h1>
)
}在类外为类追加
defaultProps
属性,这种方式会一直生效。1
2
3
4
5
6
7
8
9
10
11
12class App extends Component {
render() {
return (
<div>
{this.props.name}
</div>
);
}
}
App.defaultProps={
name:"jack"
}