Javascript 检查变量是 React 节点还是数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32635867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if variable is React node or array
提问by ThomasReggi
I'd like to have a condition that states if prop is a React node then just place is as a child within a component, and if it's not, take some action to make it into a component. This way my component will be able to accept this prop as an array of strings, or an array of nodes.
我想要一个条件,如果 prop 是一个 React 节点,那么 place 就作为组件中的一个子节点,如果不是,则采取一些措施使其成为一个组件。这样我的组件将能够接受这个 prop 作为字符串数组或节点数组。
I tried to check if React.PropTypes.node
would return a boolean and it doesn't.
我试图检查是否React.PropTypes.node
会返回一个布尔值,但它不会。
Say I have a module called List
and there's a prop called items
. I'd like to be able to pass
假设我有一个名为的模块,List
并且有一个名为items
. 我希望能够通过
var items = [
"One",
"Two",
"Three"
]
as well as
也
var items = function () {
return (
<li>One</li>
<li>Two</li>
<li>Three</li>
)
}
And within the component have some logic that would detect the difference and if it's a plain array (not an array of nodes) be able to map the items.
并且在组件内有一些逻辑可以检测差异,如果它是一个普通数组(不是节点数组),则能够映射项目。