vue使用slot分发内容与react使用prop分发内容

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 进行传递。

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

推荐阅读更多精彩内容

  • 组件(Component)是Vue.js最核心的功能,也是整个架构设计最精彩的地方,当然也是最难掌握的。...
    六个周阅读 5,665评论 0 32
  • 以下内容是我在学习和研究Vue时,对Vue的特性、重点和注意事项的提取、精练和总结,可以做为Vue特性的字典; 1...
    科研者阅读 14,175评论 3 24
  • 摘要: 理解Vue插槽。 作者:前端小智 原文:vue 2.6 中 slot 的新用法 Fundebug经授权转载...
    Fundebug阅读 12,207评论 0 17
  • 『杂文』 午后的阳光很好,很暖和,很亲切,或站着草坪中,或坐在廊道板上,都不失为一件美好的事情。 回想起,从过年到...
    小伍日记阅读 190评论 0 1
  • W达成今天的目标400 O这样就可以顺利达成本月的目标 O需要保证文章的质量,包括内容定向,标题,图片,内容,缺一...
    傲娇的岛阳君阅读 150评论 0 0