给定一个组件接收一个函数作为子组件(回调作为子组件模式,也称为render prop模式):
<Foo>{() => <Bar/>}</Foo>
React.Children.count(props.children) === 0
在 Foo
中。
文档似乎没有提到 React.Children
仅接受有效的 React 元素,因此子函数被忽略的事实看起来很奇怪。
React.Children
如何对待非元素子元素以及为什么?
欢迎引用官方来源和/或源代码。
最佳答案
正如其他人所说,documentation声明 React.Children.count(children)
仅返回有效 React
Components
的子项数量。
React.Children
不会忽略其他类型的子对象,如果需要获取计数,只需确定根子对象中数组的长度,就像您一样在 Vanilla js中。如果你看react-motion ,您会看到他们指定 children
必须是 func
的类型:
Mouse.propTypes = {
children: PropTypes.func.isRequired
};
并且他们进一步确保只有一个 child 具有 React.Children.only
( docs ):
render(): ReactElement {
const renderedChildren = this.props.children(this.state.currentStyle);
return renderedChildren && React.Children.only(renderedChildren);
}
React 不会自行处理不同类型的子项,相反,您必须自己处理它们。我整理了一个code sandbox向您展示原因。
关于javascript - React.Children 与非元素子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52553580/