React 实现Vue的插槽功能
2021-12-21 本文已影响0人
coderhzc
怎么实现Vue的插槽功能呢?
1.第一种实现方式
父组件 App.js
import React, { Component } from "react";
import NavBar from "./NavBar";
export default class App extends Component {
render() {
return (
<div>
{/* 1. 第一种实现的方式 */}
<NavBar>
<span>左边</span>
<strong>中间</strong>
<a href="#">右边</a>
</NavBar>
</div>
);
}
}
NavBar.js页面
import React, { Component } from "react";
import "./style.css";
export default class NavBar extends Component {
render() {
console.log(this.props.children);
return (
// 1. 第一种实现的方式
<div className="nav-bar">
<div className="nav-left">{this.props.children[0]}</div>
<div className="nav-center">{this.props.children[1]}</div>
<div className="nav-right">{this.props.children[2]}</div>
</div>
);
}
}
style.css
body {
padding: 0;
margin: 0;
}
.nav-bar {
display: flex;
}
.nav-left, .nav-right {
height: 44px;
width: 70px;
background-color: red;
line-height: 44px;
text-align: center;
}
.nav-center {
flex: 1;
height: 44px;
line-height: 44px;
text-align: center;
background-color: blue;
}