需求
??我們自己寫了個(gè)組件,引用組件時(shí)想要在組件中寫入內(nèi)容绘迁,并且寫入的內(nèi)容可以被組件識(shí)別合溺、控制,用過Vue的同學(xué)肯定會(huì)立刻想到slot插槽缀台,react也支持插槽功能棠赛,下面我們用react開發(fā)一個(gè)支持插槽功能的組件。
核心思想
??父組件在子組件中傳入的三個(gè)div膛腐,這三個(gè)div會(huì)默認(rèn)通過props傳到子組件中睛约,然后我們?cè)谧咏M件中控制children的渲染即可。
<Window display={this.state.display}>
//父組件在子組件中傳入的三個(gè)div哲身,
<div papa="title">title</div>
<div papa="content">content</div>
<div papa="foot">foot</div>
</Window>
??知道了react的插槽實(shí)現(xiàn)方式辩涝,我們來實(shí)現(xiàn)一個(gè)支持插槽的組件。
完成組件Pop
import React from 'react';
import {Fragment, Component} from 'react';
import { connect } from 'react-redux'
import './index.scss'
import { Icon, Button } from 'zent'
class Pop extends Component {
constructor(props) {
super(props);
this.state = {}
this.renderChild = this.renderChild.bind(this)
}
render() {
return (
<Fragment>
<div className="pop-wrap">
<div className="pop-header">
<span className="left">{this.props.popTitle}</span>
<Icon className="right" type="close"/>
</div>
<div className="pop-content">
{Array.isArray(this.props.children) ?
this.props.children.map((child) => {
return this.renderChild(child)
}) : this.props.children && this.renderChild(this.props.children)}
</div>
<div className="pop-footer">
<Button.Group>
<Button size="small" className="cancel">取消</Button>
<Button size="small" type="primary" className="confirm">確定</Button>
</Button.Group>
</div>
</div>
</Fragment>
)
}
renderChild (child) { // 控制內(nèi)容的分發(fā)
if (child.props.left) {
return <div className="left" key="left">{child}</div>
} else if (child.props.right) {
return <div className="right" key="right">{child}</div>
} else if (child.props.center) {
return <div className="center" key="center">{child}</div>
}
}
}
const mapStateToProps = (state) => {
return {
}
}
const mapDispatchToProps = (dispatch) => {
return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(Pop)
Pop的scss文件
.pop-wrap {
position:absolute;
left:0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
z-index: 2;
width: 350px;
height: 300px;
border: 1px solid #C8C8C8;
border-radius: 2px;
}
.pop-header {
height: 40px;
display: flex;
align-items: center;
border-bottom: 1px solid #C8C8C8;
.left{
flex: 10;
margin-left: 10px;
}
.right {
flex: 1;
margin-right: 10px;
}
}
.pop-content {
display: flex;
height: 220px;
.left, .right, .center {
display: flex;
justify-content: center;
padding-top: 10px;
}
.left,.right {
flex: 1;
}
.center {
width: 100%;
}
.right{
border-left: 1px solid #C8C8C8;
}
}
.pop-footer {
height: 40px;
display: flex;
align-items: center;
border-top: 1px solid #C8C8C8;
flex-direction: row-reverse;
.cancel, .confirm{
margin-right: 10px;
}
}
引用子組件