这是我参与8月更文挑战的第八天,活动详情查看:8月更文挑战
1. children
- children属性:表示组件标签的子节点。当组件标签有子节点时,props就会有该属性。
function Hello(props){
return(
<div>
{props.children}
</div>
)
}
<Hello>我是子节点</Hello>
1.1 子节点的三种形式
- 文本子节点
const App = props=>{
console.log(props)
props.children()
return(
<div>
{props.children}
</div>
)
}
ReactDOM.render(<App>文本子节点</App>,document.getElementById('root'))
- JSX子节点
const App = props=>{
console.log(props)
props.children()
return(
<div>
{props.children}
</div>
)
}
ReactDOM.render(<App><p>我是p标签</p></App>,document.getElementById('root'))
- 组件子节点
const Test = ()=> <button>button组件</button>
// children 为文本节点
const App = props=>{
console.log(props)
props.children()
return(
<div>
{props.children}
</div>
)
}
ReactDOM.render(<App><Test/></App>,document.getElementById('root'))
- 函数子节点
const App = props=>{
console.log(props)
props.children()
return(
<div>
{props.children}
</div>
)
}
ReactDOM.render(<App>{
()=> console.log("object")
}</App>,document.getElementById('root'))
1.2 总结
- children只是props的一个属性。表示组件标签的子节点当组件标签有子节点时,props就会有该属性。
- children属性与普通的props一样,值可以是任意值(文本、JSX、组件、函数)
2. props校验
2.1 为什么 要校验
-
对于组件来说,props是外来的,无法保证组件使用者传入什么格式的数据
-
传入不是校验规定的数据类型 会导致组件内部报错。
/**
* props 检验
*/
const App = props =>{
const arr = props.colors
const lis = arr.map((item,index)=><li key={index}>{item.name}</li>)
return <ul>{lis}</ul>
}
ReactDOM.render(<App colors={19}/>,document.getElementById('root'))
- 关键问题:组件的使用者不知道明确的错误原因
2.2 校验的使用
- props校验:允许在创建组件的时候,就指定props的类型、格式。
- 作用:捕获使用组件时因为props导致的错误
安装prop-types
npm install prop-types --save
或
yarn add prop-types
导入prop-types包
import PropTypes from 'prop-types';
使用组件名.propTypes = { } 来给组件的props添加校验规则
const App = props =>{
const arr = props.colors
const lis = arr.map((item,index)=><li key={index}>{item.name}</li>)
return <ul>{lis}</ul>
}
App.propTypes ={
colors:propTypes.array
}
ReactDOM.render(<App colors={19}/>,document.getElementById('root'))
- 校验规则通过propTypes对象来指定
虽然arr.map报错还在 但是控制台中给出了具体的错误提示。
- 把数据换成数组格式
ReactDOM.render(<App colors={['red','blue']}/>,document.getElementById('root'))
- 正确渲染
2.3 约束规则
-
常见类型 array bool func number object string
-
React元素类型:element
-
必填项:isRequired
requiredFunc:PropTypes.func.isRequired,
- 特定结构的对象:shape({ })
App.propTypes ={
a:propTypes.number,
fn:propTypes.func.isRequired,
tag:propTypes.element,
filter:propTypes.shape({
area:propTypes.string,
price:propTypes.number
})
}
3. props的默认值
- 场景:分页组件 每页显示条数
- 作用:给props设置默认值,在未传入props时生效
/**
* props 检验
*/
const App = props => {
return(
<div> {props.pageSize}</div>
)
}
App.defaultProps = {
pageSize: 10
}
ReactDOM.render(<App />, document.getElementById('root'))
当想传入值的时候,就以传入值为准。