我正在尝试映射片段的子节点,片段又是组件的子节点。例如:
const Frag = () => (
<React.Fragment key="test-key">
<div>test1</div>
<div>test2</div>
</React.Fragment>
);
const Outer = ({ children }) => (
<div>
{
React.Children.map(children, (child) => (
<a>
{child}
</a>
))
}
</div>
);
// Usage
<Outer>
<Frag />
</Outer>
这将导致单个a
标记,即使该片段内部有多个div。文档(https://reactjs.org/docs/react-api.html#reactchildrenmap)似乎表明这应该与键控片段一起使用,我认为我正在创建一个键控片段(https://reactjs.org/docs/fragments.html#keyed-fragments)。任何帮助将不胜感激!
答案 0 :(得分:2)
是的,但就我所知 - 你正在迭代Outer
个孩子。
尝试
React.Children.map(children[0].props.children, (child) => (
但是,仔细查看您的链接 - 我发现文档说错了
该函数永远不会传递容器对象
这是一个例子,它清楚地表明容器被传递给函数:
<script src="https://unpkg.com/@babel/standalone/babel.js"></script>
<script src="https://unpkg.com/react@16.2.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.2.0/umd/react-dom.development.js"></script>
<div id="root" />
<script type="text/babel">
const Frag = () => (
<>
<div>test1</div>
<div>test2</div>
</>
);
const Outer = ({ children }) => (
<div>
{
React.Children.map(children, (child) => console.log(`Child type is ${child.type.name || child.type.toString()}`) || (
<a>
{child}
</a> ))
}
</div>
);
ReactDOM.render((
<div>
<Outer>
<>
<div>test1</div>
<div>test2</div>
</>
</Outer>
<Outer>
<Frag />
</Outer>
</div>
), document.getElementById('root'));
</script>
&#13;