获取react元素字符串类型

Get react element string type

本文关键字:类型 字符串 元素 react 获取      更新时间:2023-09-26

如果我有一个呈现以下内容的组件:

<div>
  <Example/>
  <span>hi</span>
</div>

属性this.props.children将是一个包含两个元素的数组。当循环child.type只适用于span返回字符串span时,有什么属性会给我一个反应元素的字符串Example ?

如果组件类有一个显示名,您应该能够使用child.type.displayName

无论它是原生DOM元素还是ReactElement,都可以使用此方法获取字符串。

function getStringType (node) {
  if (typeof node.type === 'string') return node.type
  if (node.type && node.type.displayName) return node.type.displayName
  return false
}