鍍金池/ 問答/HTML/ react如何實(shí)現(xiàn)內(nèi)容分發(fā),組件中的代碼會(huì)如何渲染

react如何實(shí)現(xiàn)內(nèi)容分發(fā),組件中的代碼會(huì)如何渲染

在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中的插槽是怎么實(shí)現(xiàn)的呢?如下代碼中的Parent組件渲染出來的代碼應(yīng)該是什么樣子的呢?

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>
    )
  }
}

是會(huì)渲染成

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

還是其他什么樣式?渲染的原理是什么呢?

回答
編輯回答
哚蕾咪
<div className='parent'>
    <Child>
      <p>content</p>
    </Child>
  </div>

會(huì)渲染成如下:

<div className='parent'>
    <div className='child'>
     <div>hahah</div> 
     <div>wwww</div>
  </div>
</div>
<Child>
  <p>content</p>
</Child>
// <p>content</p> 會(huì)當(dāng)成 Child 的 props.children 往下傳。
2017年3月4日 18:01