vue
將 <slot>
元素作爲承載分發內容的出口
// layout.vue
<div class="container">
<main>
<slot></slot>
</main>
</div>
當組件渲染的時候,<slot></slot>
將會被替換該組件起始標籤和結束標籤之間的任何內容
// hone.vue
<div class="container">
<layout>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</layout>
</div>
react
每個組件都可以獲取到 props.children
。它包含組件的開始標籤和結束標籤之間的內容。
class Layout extends Component {
render() {
return (
<div className="container">
<main>
{this.props.children}
</main>
</div>
);
}
}
props
是 React 組件的輸入。它們是從父組件向下傳遞給子組件的數據。
function Home (params) {
return (
<>
<Layout>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</Layout>
</>
)
}
vue
有時我們需要多個插槽。對於這樣的情況,<slot>
元素有一個特殊的特性:name
。這個特性可以用來定義額外的插槽:
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
一個不帶 name 的 <slot>
出口會帶有隱含的名字“default”
在向具名插槽提供內容的時候,我們可以在一個 <template>
元素上使用 v-slot
指令,並以 v-slot
的參數的形式提供其名稱:
<layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</layout>
現在 <template>
元素中的所有內容都將會被傳入相應的插槽。任何沒有被包裹在帶有 v-slot
的 <template>
中的內容都會被視爲默認插槽的內容。
react
注意:組件可以接受任意 props,包括基本數據類型,React 元素以及函數。
class Layout extends Component {
render() {
return (
<div className="container">
<header>
{this.props.header}
</header>
<main>
{this.props.children}
</main>
<footer>
{this.props.footer}
</footer>
</div>
);
}
}
少數情況下,你可能需要在一個組件中預留出幾個“洞”。這種情況下,我們可以不使用 children
,而是自行約定:將所需內容傳入 props
,並使用相應的 prop
。
function Home (params) {
return (
<>
<Layout
header={
<h1>Here might be a page title</h1>
}
footer={
<p>Here's some contact info</p>
} >
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</Layout>
</>
)
}
React 元素本質就是對象(object),所以你可以把它們當作 props,像其他數據一樣傳遞。這種方法類似Vue“槽”(slot
)的概念,但在 React 中沒有“槽”這一概念的限制,你可以將任何東西作爲 props
進行傳遞。