props属性
在使用组件的时候可以向组件传递数据,在组件内我们可以使用props这个对象来调用我们的数据。
类组件
此时如果我们使用组件的时候传入了值,那么怎么获取这个值呢?
ReactDOM.render(,document.getElementById("app"))
我们输出props查看一下,这个组件天生就有这个props属性
class Person extends React.Component{
render(){
console.log(props)
return
hello
}
}
此时就可以在控制台看到
其实this就是这个组价中的实例对象,我们可以输出this看到,我们传入的值就在这个实例对象的props中
所以我们可以通过this.props来获取我们传入的值
class Person extends React.Component{
render(){
console.log(this)
return
hello
{this.props.name}
}
}
函数组件
{props.name}
注意
-
props在组件内只是可读的,组件内不能修改我们的props
-
如果props的数据源被修改,那么组件内得到的props数据也会随着修改(数据驱动DOM)
此时我们在使用组件的时候没有传入值,看一下此时输出的this,此时的props中没有值
我们可以使用defaultProps设置默认值,一般用于props未赋值,但又不能为null的情况
class Person extends React.Component{
static defaultProps={
name:'小明'
}
render (){
console.log(this)
return
hello
}
}
ReactDOM.render( ,document.getElementById("app"))
在类组件中我们使用static关键字,给defaultProps 属性定义内容
函数组件
在函数组件中,直接给函数名后面添加一个defaultProps属性就可以初始化我们的props值