react插槽--默认插槽,具名插槽

不具名插槽

Props.js
import Layout from "./Layout";
// 函数式组件传值
export default function Props() {
  return (
    <Layout title="函数式传值">
    <div>
        <h3>函数式传值</h3>
        <p>不具名插槽</p>
    </div>
    </Layout>
  )
Layout.js
import React, { Component } from "react";
export default class Layout extends Component {
  componentDidMount() {
    const { title = "react" } = this.props;
    document.title = title;
  }
  render() {
    const {children,title = "react"} = this.props
    return (
      <div style={{backgroundColor:"red"}}>
        <h3>{title}</h3>
        {children}
      </div>
    );
  }
}

运行效果:
在这里插入图片描述

具名插槽

Props.js
import React, { Component } from "react";
import Layout from "./Layout";
export default function Props() {
  return (
    <Layout title="函数式传值">
      {{
        btn: <button>按钮</button>,
        content: "我是内容",
    }}
    </Layout>
  )
}
Layout.js
import React, { Component } from "react";
export default class Layout extends Component {
  componentDidMount() {
    const { title = "react" } = this.props;
    document.title = title;
  }
  render() {
    const {children,title = "react"} = this.props
    const a = [];
    if (children.$$typeof) {
      a.push(children);
    } else {
      for (let item in children) {
        a.push(children[item]);
      }
    }
    return (
      <div style={{backgroundColor:"red"}}>
        <h3>{title}</h3>
        //单独执行某一个
        {children.btn}
        //全部遍历执行
         {a.map((item, index) => {
          return <div key={"child" + index}>{item}</div>;
        })}
      </div>
    );
  }
}

运行效果:
在这里插入图片描述

posted @ 2022-03-03 08:42  Cupid05  阅读(237)  评论(0编辑  收藏  举报