1.children属性
表示组件标签的子节点。当组件标签有子节点时,props就会有该属性。子节点可以传入各种类型的数据(文本、React元素、组件、甚至是函数)
- const Hello = props=>{
- return(
- <div>
- 组件的子节点:{props.children}
- div>
- )
- }
- ReactDOM.render(<Hello>我是子节点Hello>,//调用的是父组件
-
- document.getElementById('root'))
- const Test = ()=>{
- return(
- <button>我是Test组件button>
- )
- }
-
- const Hello = props=>{
- return(
- <div>
- 组件的子节点:{props.children}
- div>
- )
- }
- ReactDOM.render(<Hello><Test/>Hello>,//调用的是父组件
-
- document.getElementById('root'))

- const Hello = props=>{
- console.log(props)
- props.children()
- return(
- <div>
- 组件的子节点:{props.children}
- div>
- )
- }
- ReactDOM.render(<Hello>{()=>console.log('这是一个函数子节点')}Hello>,//调用的是父组件
-
- document.getElementById('root'))

2.1props校验
-
- //小明创建的组件
- const App =props=>{
- const arr =props.colors
- const lis = arr.map((item,index)=>
- <li key={index}>{item}li>)
- return(
- <ul>{lis}ul>
- )
- }
-
- //小红创建组件App
- <App colors={19}/>
2.2什么是props检验
2.3props校验使用步骤
- //小明创建的组件
- const App =props=>{
- const arr =props.colors
- const lis = arr.map((item,index)=>
- <li key={index}>{item}li>)
- return(
- <ul>{lis}ul>
- )
- }
-
- App.PropTypes={
- //约定colors属性为array类型
- //如果类型不对,则报出明确错误,便于分析错误
- colors:PropTypes.array
- }
-
-
-
- ReactDOM.render(<App colors={19}/>,//调用的是父组件
-
- document.getElementById('root'))
2.3props约束规则
- //小明创建的组件
- const App =props=>{
- const arr =props.colors
- const lis = arr.map((item,index)=>
- <li key={index}>{item}li>)
- return(
- <ul>{lis}ul>
- )
- }
-
- App.PropTypes={
- //约定colors属性为array类型
- //如果类型不对,则报出明确错误,便于分析错误
- colors:PropTypes.array,
- a:PropTypes.number,
- fn:PropTypes.func.isRequired,//设置函数为必填项
- tag:PropTypes.element,
- filter:PropTypes.shape({
- area:PropTypes.string,
- price:PropTypes.number
- })
-
- }
-
-
-
- ReactDOM.render(<App colors={['red','green','blue']}/>,//调用的是父组件
-
- document.getElementById('root'))
报错:

3.props的默认值
作用:给props设置默认值,在未传入props时生效
- const App =props=>{
- const arr =props.colors
- const lis = arr.map((item,index)=>
- <li key={index}>{item}li>)
- return(
- <ul>{lis}ul>
- )
- }
-
- App.defaultProps={
- colors:['red','green','blue']
- }
-
- ReactDOM.render(<App/>,//调用的是父组件
-
- document.getElementById('root'))