介绍
组件是独立且封闭的单元,只能使用组件自己的数据,在组件化过程中,我们将一个完整
的功能拆分多个组件,以便于更好的完成整个应用的功能。而在这个过程中,多个组件之间
不可便面的要共享某些数据。
为了实现这些功能,就需要打破组件之间独立封闭性
特点
1.可以给组件传递任意类型的数据
<Hello name="Jack" age={18} colors={['red','yellow','blue']} ></Hello>
2.props是只读对象,不能对props的值进行修改
3.针对类组件时,如果写了构造函数,应该将props传递给super(),否则构造函数无法获取到props
class App extends React.Component{
constructor(props){
super(props);
console.log(this.props);
}
render(){
return (
<div className='ceshi'>{this.props.name}</div>
)
}
}
组件的porps
组件是封闭的,需要接受来自外部的数据
porps的作用:接受传递给组件的数据
传递数据
给组件标签添加属性
<Hello name="Jack" age={18}></Hello>
接受数据
函数组件通过参数pros接受参数
function Hello(pros){
console.log(props);
return (
<div>接受到的数据 {props.name}</div>
)
}
类组件通过this.pros接受参数
class Hello extends React.Component {
constructor(props){
// 如果不添加super(props)的话,构造函数中无法获取props的数据
super(props);
console.log(this.props);
}
render(){
return(
<div>接受的数据 {this.props.age}</div>
)
}
}
Props
Children
组件标签的子节点。当组件标签有子节点时,props就会有该属性
children属性与普通的props一样,值可以为(任意值 文本 React元素 组件 甚至函数 JSX)
props校验
对于组件来说props是外来的,无法保证组件使用者传入的为什么格式的数据
作用:
捕获使用组件是因为props导致的错误,并且给出明确的错误提醒,提示开发者所传递数据类型不符的相关信息,增强组件的健壮性
function App(props){
const arr = props.colors;
const lis = arr.map((item,index)=><li key={index}>{item.name}</li>)
return (
<ul>{lis}</ul>
)
}
// 使用组件者
<App colors={19}>
使用步骤
1.安装prop-types
yarn add prop-types
npm i prop-types
2.导入prop-types
yarn add prop-types
npm i prop-types
3.使用 组件名.propTypes = {} 来给组件的props添加校验规则
App.PropTypes = {
// 约定color的属性为array类型
// 如果数据类型不对,则会进行报错
colors:PropTypes.array
}
4.校验规则通过propType对象来指定
具体代码如下所示:
import PropTypes from 'prop-types'
function App(props){
return (
<h1>hi,{props.colors}</h1>
)
}
App.PropTypes = {
colors:PropTypes.array
}
约束规则
1.数据类型
array bool func number objcet string
2.React元素类型 element
3.必填项 isRequired
4.特定结构的对象 shape({})
常见类型
opetionalFunc:PropTypes.func
// 必填项
requiredFunc:PropTypes.func.isRequired
// 特定结构的对象
optionalObjectWithShape:PropTypes.shape({
color:PropTypes.string,
fontSize:PropTypes.number
})
实例代码
App.PropTypes = {
// 指定a为number类型
a:PropTypes.number,
// 指定fn的传递数据为函数类型,且不能为空
fn:PropTypes.func.isRequired,
// 指定tag所传递的数据类型为element
tag:PropTypes.element,
// 指定特定结构的的对象 area所传递的数据为字符类型 price所传递的数据类型为number类型
filter:PropTypes.shape({
area:PropTypes.string,
price:PropTypes.number
})
}
props默认值
Props默认值在React开发中是一个十分重要的概念,它能让我们在不同场景下灵活的使用组件
以下为实例代码
//引入模块
import React from "react";
import ReactDOM from "react-dom";
const App = props =>{
console.log(props)
return (
<div>展示默认值:{props.pageSize}</div>
)
}
// 设置默认值
App.defaultProps = {
pageSize:10
}
ReactDOM.render(<App/>,document.getElementById('root'));
注意:我们在使用的过程中应注意 Props默认值在未传入Props时才会生效