react实现插槽案例
原创
©著作权归作者所有:来自51CTO博客作者wg_iGBFcBFB的原创作品,请联系作者获取转载授权,否则将追究法律责任
import React, { Component } from 'react'
// import NavBar from './NavBar'
import NavBar2 from './NavBar-2'
export default class App extends Component {
render() {
return (
<div>
{/* <NavBar>
<span>AAA</span>
<strong>bbb</strong>
<a href="https://www.baidu.com/">ccc</a>
</NavBar> */}
<NavBar2 leftSlot={ <span>AAA</span> }
centerSlot={ <strong>bbb</strong> }
rightSlot={ <a href="https://www.baidu.com/">ccc</a> }
/>
</div>
)
}
}
----------------
body{
padding: 0;
margin: 0;
}
.nav-bar{
display: flex;
}
.nav-item {
height: 44px;
line-height: 44px;
text-align: center;
}
.nav-left, .nav-right {
width: 70px;
skyblue;
}
.nav-center{
flex: 1;
orangered;
}
---------1----------
import React, { Component } from 'react'
import './style.css'
export default class NavBar extends Component {
render() {
console.log(this.props.children);
return (
<div className="nav-bar">
<div className="nav-item nav-left"> {this.props.children[0]} </div>
<div className="nav-item nav-center"> {this.props.children[1]} </div>
<div className="nav-item nav-right"> {this.props.children[2]} </div>
</div>
)
}
}
-----------2 具名插槽-----------
import React, { Component } from 'react'
import './style.css'
export default class NavBar extends Component {
render() {
// console.log(this.props);
const {leftSlot,centerSlot,rightSlot} = this.props;
return (
<div className="nav-bar">
<div className="nav-item nav-left"> {leftSlot} </div>
<div className="nav-item nav-center"> {centerSlot} </div>
<div className="nav-item nav-right"> {rightSlot} </div>
</div>
)
}
}