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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:00:31  来源:igfitidea点击:

Check if variable is React node or array

javascriptpropertiesreactjs

提问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.nodewould return a boolean and it doesn't.

我试图检查是否React.PropTypes.node会返回一个布尔值,但它不会。

Say I have a module called Listand 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.

并且在组件内有一些逻辑可以检测差异,如果它是一个普通数组(不是节点数组),则能够映射项目。

回答by ThomasReggi

React has a function just to check if a variable is an element, here's the docs.

React 有一个函数来检查一个变量是否是一个元素,这里是docs

React.isValidElement()