React 实现Vue的插槽功能

怎么实现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;
}

实际截图

image.png

2.第二中方式实现

实际截图

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容