1. 匿名插槽 ---> 类似于 vue 中的v-slot
function Dialog(props) {
return <div style={{ border: "1px solid blue" }}>{props.children}</div>
}
export default function Composition() {
return (
<div>
<Dialog>
<h1>组件复合</h1>
<p>复合组件给与你足够的敏捷去定义自定义组件的外观和行为</p>
</Dialog>
</div>
)
}
2. 具名插槽-----> 类似于vue 中的v-slot:footer
function Dialog(props) {
return <div style={{ border: "1px solid blue" }}>
{props.children.default}
<div>
{props.children.footer}
</div>
</div>
}
export default function Composition() {
return (
<div>
<Dialog>
{{
default: (
<frameElement>
<h1>组件复合</h1>
<p>复合组件给与你足够的敏捷去定义自定义组件的外观和行为</p>
</frameElement>
),
footer: (
<>
<button onClick={() => alert("react确实好")}>确定</button>
</>
)
}}
</Dialog>
</div>
)
}
3. 作用域插槽----> 类似于vue 中的v-slot:footer="ctx"
function Dialog(props) {
// 备选消息
const messages = {
"foo": {title: 'foo', content: 'foo11111~'},
"bar": {title: 'bar', content: 'bar~'},
}
// 执行函数获得要显示的内容
const {body, footer} = props.children(messages[props.msg]);
return <div style={{ border: "1px solid blue" }}>
{body}
<div>
{footer}
</div>
</div>
}
export default function Composition() {
return (
<div>
{/* 执行显示消息的key */}
<Dialog msg="foo">
{({title, content}) => ({
body: (
<>
<h1>{title}</h1>
<p>{content}</p>
</>
),
footer: <button onClick={() => alert("react确实好")}>确定</button>
})}
</Dialog>
</div>
)
}