在React v16.2.0中,有一个新的接口调用React.Children。
我很好奇React.Children和直接使用children有什么不同。
例如,如果我想操作子内容,我可以用这两种方法来操作。example
const Child = () => (
<div>child</div>
)
class App extends React.Component {
render() {
const template1 = React.Children.map(this.props.children, (child) => {
return React.cloneElement(child);
});
const template2 = this.props.children.map((child) => {
return React.cloneElement(child);
});
return [template1, template2];
}
}结果是一样的。
有谁知道有什么不同吗?
或者react团队发布此API的目的是什么。
谢谢。
发布于 2018-03-15 12:59:29
据我所知,对于你们的操作来说没有什么真正的区别。但是,React.Children提供了用于处理this.props.children的实用程序。关于map的用法,在the documentation中有一条我认为可能很有趣的评论:
如果子项是键控片段或数组,则将遍历它,则为
因此,他们的实现似乎比您刚刚使用的Array.prototype.map要多做一些事情。
您可以在其他functionality React.Children provides上阅读,但它们似乎提供了方便的功能,因此您不必担心遍历可能有孩子的孩子等等。
发布于 2019-04-22 04:24:44
React组件的子节点可能是未定义或为空的节点。React.Children.map是一个实用函数,可以帮助您处理不同的情况。
对包含在此设置为thisArg的子级中的每个直接子级调用一个函数。如果孩子是一个数组,它将被遍历,并为数组中的每个孩子调用函数。如果子代为null或undefined,此方法将返回null或undefined而不是数组。
您应该始终使用React.Children.map来遍历子应用程序中的子项。当子元素不是数组时,使用children.map会抛出错误。
发布于 2019-06-10 19:07:48
请看一下这个例子,看看不同之处
将此内容粘贴到控制台浏览器:
var children = null
chidren.map(i => {return i}) // => VM370:1 Uncaught TypeError: Cannot read property 'map' of null
React.Children.map(children, i => {return i;}) // return null下面是结果:result
因此,当子项为null或未定义时,React.Children.map将处理这种情况
https://stackoverflow.com/questions/49291442
复制相似问题