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>
);
}
}
运行效果:
请用今天的努力,让明天没有遗憾。