首页 > 解决方案 > React - map over actual HTML children wrapped in HoC

问题描述

I have a Component that renders all the children passed to it as list elements. For example:

// more or less the logic of my component
const ListifyChildren = (props) => {
  return <ul>{props.children.map(element => <li>{element}</li>)}</ul>
}

// example use
<ListifyChildren>
  <div>Some component</div>
  <div>Some other component</div>
</ListifyChildren>

Would produce

<ul class="listify">
  <li class="listify-list-item">Some component</li>
  <li class="listify-list-item">Some other component</li>
</ul>

But the problem is I want to be able to use HoC's that return a list of components and to treat those components as children of my actual list. For example:

const ReturnSomeStuff = () => {
 return [someArray].map(element => <div>{element}</div>
}

<ListifyChildren>
  <ReturnSomeStuff/>
</ListifyChildren>

//what I get:
<ul class="listify">
  <li class="listify-list-item">
   <div>something</div>
   <div>something</div>
   <div>something</div>
  </li>
</ul>

//what I want to get:
<ul class="listify">
   <li class="listify-list-item">something</li>
   <li class="listify-list-item">something</li>
   <li class="listify-list-item">something</li>
</ul>

How can I make sure that my component maps over actual html children, not the function calls passed to it?

标签: javascriptreactjs

解决方案


我找到了答案:关键是通过React.Children API引用子元素,而不是简单的 props.children - 它返回渲染元素的列表。


推荐阅读