javascript - 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?
解决方案
我找到了答案:关键是通过React.Children API引用子元素,而不是简单的 props.children - 它返回渲染元素的列表。
推荐阅读
- javascript - Javascript 比较 window.pageYOffset 奇怪的逻辑
- r - RStudio - 相关矩阵
- android - 可以使用新的应用内评论吗?
- python - 如何获取二维 numpy 数组中每一行的前 2 个值的索引,但不包括特定区域?
- reactjs - 如何将组件及其值作为道具传递
- python - Python 2.7 没有为 ios build 编译配方
- r - R函数确定两个日期间隔之间的重叠——DescTools间隔函数
- python - 是否可以在 Python 的 igraph 中调整边缘标签的字体大小?
- excel - 如果列标题符合某些文本条件,则对列中的所有行求和
- xml - XML 文档是否有像 HTML 这样的结束标签?