5、react卡槽

 1 react分为聚名卡槽和匿名卡槽两种
 2 
 3 
 4 
 5 import React,{Component} from 'react'
 6 import Layout from './Layout'
 7 import {Consumer} from '../Appcontent'
 8 
 9 class Home extends Component{
10     render(){
11         return <Consumer>{ctx => <HomeHandle {...ctx}/>}</Consumer>
12     }
13 }
14 
15 export default Home;
16 
17 
18 聚名卡槽传递一个对象:
19 function HomeHandle(props){
20     return(
21         <Layout title='商城首页'>
22                  {{
23                     btn: <button>按钮</button>,
24                     content:"我是内容"
25                 }}
26         </Layout>
27     )
28 }
29 
30 匿名卡槽
31 // function HomeHandle(props){
32 //     return(
33 //         <Layout title='商城首页'>
34 //               <div>Home</div>
35 //         </Layout>
36 //     )
37 // }
 1 Layout 文件
 2 
 3 import React,{Component} from 'react'
 4 import TabBar  from '../component/TabBar'
 5 
 6 class Layout extends Component{
 7     render(){
 8         const {showTabBar=true, children} = this.props
 9         console.log('this.props', this.props)
10        
11         //兼容匿名聚名卡槽写法
12         const a =[]
13         if(children.$$typeof){//匿名卡槽chuldren携带有$$typeof,里面直接包含传递内容
14             a.push(children)
15         }else{
16             for(let i in children){//聚名卡槽children则携带命名的对象名
17                 a.push(children[i])
18             }
19         }
20         return (
21             <div>
22                 {/* {children.btn}
23                 {children.content} */}
24                 {
25                     a.map((itme,index)=>{
26                         return <div key={`chuldren${index}`}>{itme}</div>
27                     })
28                 }
29                 {showTabBar && <TabBar />}
30             </div>
31         )
32     }
33     componentDidMount(){
34         const {title='商城'} = this.props
35         document.title = title
36     }
37 }
38 
39 export default Layout;
40 
41 
42 
43 Layout文件中引入的TabBar文件:
44 
45 import React,{Component} from 'react';
46 import {Consumer} from '../Appcontent'
47 class TabBar extends Component{
48     render(){
49         return(
50             <Consumer>{ctx => <TabBarHandle {...ctx}/>}</Consumer>
51         )
52     }
53 }
54 
55 export default TabBar;
56 
57 function TabBarHandle(props){
58     return <div className='TabBar'>TabBarHandle</div>
59 }

 

 
posted @ 2020-09-01 23:36  雪糕战士  阅读(181)  评论(0编辑  收藏  举报