react如何实现内容分发,组件中的代码会如何渲染

在vue中有slot,能把组件中的元素插入到指定位置,代码如下

<!-- Child -->
<template>
  <!-- 必须有根元素 -->
  <div class="child">
    <slot name="header"></slot>
    <slot></slot>
    <slot name="footer"></slot>
  </div>
</template>
<script>
  export default {}
</script>

<!-- Parent -->
<template>
  <div class="parent">
    <child>
      <p slot="header">header</p>
      <p>content</p>
      <p slot="footer">footer</p>
    </child>
  </div>
</template>
<script>
  import Child from './Child'
  export default {
    components: {Child}
  }
</script>

那么react中的插槽是怎么实现的呢?如下代码中的Parent组件渲染出来的代码应该是什么样子的呢?

class Child extends React.Component<IChildProps, void> {
  render () {
    return (
      <div className='child'>
         <div>hahah</div> 
         <div>wwww</div>
      </div>
    )
  }
}

class Parent extends React.Component<{}, void> {
  render () {
    return (
      <div className='parent'>
        <Child>
          <p>content</p>
        </Child>
      </div>
    )
  }
}

是会渲染成

<div className='child'>
     <div>hahah</div> 
     <div>wwww</div>
     <p>content</p>
</div>

还是其他什么样式?渲染的原理是什么呢?

阅读 3.4k
1 个回答
<div className='parent'>
    <Child>
      <p>content</p>
    </Child>
  </div>

会渲染成如下:

<div className='parent'>
    <div className='child'>
     <div>hahah</div> 
     <div>wwww</div>
  </div>
</div>
<Child>
  <p>content</p>
</Child>
// <p>content</p> 会当成 Child 的 props.children 往下传。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题