写页面的时候最常碰见header 、content 、 footer 这种布局 , 当然不局限于这种 只要页面多数都要用到的组件都可以。
如果不使用组件复合 封装成组件后挨个引入感觉还是差点意思
做个小demo
主组件:
import React, { Component } from 'react'
import Layout from './Layout'
export default class index extends Component {
render() {
return (
<Layout bottom={true} top={true} title={"首页"}>
<div>中间显示的文字</div>
</Layout>
)
}
}
layout:
import React, { Component } from 'react'
const divStyle = {
width: '100%',
height: '100px',
textAlign: 'center',
lineHeight: '100px'
}
export default class Layout extends Component {
componentDidMount() {
document.title = this.props.title || "未设置"
}
render() {
const { children, top, bottom } = this.props
return (
<>
{top && <header style={divStyle}>header</header>}
{children}
{bottom && <footer style={divStyle}>footer</footer>}
</>
)
}
}
这里涉及到props.children 组件通过<div></div>
这种形式写 中间的内容会自动被props.children接收
这种写法还可以继续扩展
扩展demo
主组件
import React, { Component } from 'react'
import Layout from './Layout'
export default class index extends Component {
render() {
return (
<Layout bottom={true} top={true} title={"首页"}>
{{
content: <div>内容</div>,
btnClick: () => {console.log("click me!")}
}}
<div>中间显示的文字</div>
</Layout>
)
}
}
layout
import React, { Component } from 'react'
const divStyle = {
width: '100%',
height: '100px',
textAlign: 'center',
lineHeight: '100px'
}
export default class Layout extends Component {
componentDidMount() {
document.title = this.props.title || "未设置"
}
render() {
const { children, top, bottom } = this.props
console.log(this.props)
return (
<>
{top && <header style={divStyle}>header</header>}
{children[0].content}
<button onClick={children[0].btnClick}>click me!</button>
{bottom && <footer style={divStyle}>footer</footer>}
</>
)
}
}
这里的children的表现:
变成了一个数组 由于我没有挂载
中间显示的文字
这个dom 所以不会显示