react 三大属性值之一
props
,获取标签属性上的属性值,函数组件和class组件都有这个属性。
函数组件
- 简单的使用
function Demo(props){
return (
// 获取标签上传入的name属性值
<div>我是:{props.name}</div>
)
}
ReactDOM.render(<Demo name="Tom" />, document.getElementById("app))
- 限制传入属性值得类型和默认值
- 15版本以前 PropTypes 在React核心库上,16版本以后,PropTypes 独立出一个依赖包
- 需要引入prop-types这个依赖包
function Demo(props){
return (
// 获取标签上传入的name属性值
<div>我是:{props.name}, 性别:{props.sex}, 年龄:{props.age}</div>
)
}
Person.propTypes = {
name: PropTypes.string.isRequired, // 限制name必传,且为字符串
sex: PropTypes.string, // 限制sex为字符串
age: PropTypes.number, // 限制age为数值
}
// 指定标签属性的默认值
Person.defaultProps = {
sex: '男', // sex默认值为男
age: 18 // age默认值为18
}
ReactDOM.render(<Demo name="Tom" />, document.getElementById("app))
class 组件
- 简单使用
class Person extends React.Component {
render(){
// 获取标签上的属性值
const {name, sex, age} = this.props;
return (
<ul>
<li>姓名:{name}</li>
<li>性别:{sex}</li>
<li>年龄:{age}</li>
</ul>
)
}
}
ReactDOM.render(<Person name="jerry" age={19} sex="男" />, document.getElementById("app"))
- 对props 属性值进行限制
- 使用static 限制定义在组件原型上
class Person extends React.Component {
render(){
// 获取标签上的属性值
const {name, sex, age} = this.props;
static propTypes = {
name: PropTypes.string.isRequired, // 限制name必传,且为字符串
sex: PropTypes.string, // 限制sex为字符串
age: PropTypes.number, // 限制age为数值
speak: PropTypes.func // 限制speak为函数
}
// 指定标签属性的默认值
static defaultProps = {
sex: '男', // sex默认值为男
age: 18 // age默认值为18
}
return (
<ul>
<li>姓名:{name}</li>
<li>性别:{sex}</li>
<li>年龄:{age}</li>
</ul>
)
}
}
ReactDOM.render(<Person name="jerry" age={19} sex="男" />, document.getElementById("app"))
- class 的constructor(构造器)的参数会接收到props
class Demo extends React.Component{
constructor(props) {
// 先通过super将传入的值传到React.Component的constructor,在组件的constructor 就可以访问到this.props;
super(props)
}
}
总结:props 属性是接收组件标签上的属性值,以对象(key-value)的形式保存到props上。
要对props的属性进行类型限制和设置默认值,在15.x版本及以前
直接使用React.propTypes.xxx,16.x版本及以后
需要引入prop-types
包(使用ts开发可以忽略)