最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get react element string type - Stack Overflow

programmeradmin4浏览0评论

If I have a ponent that renders the following:

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

The property this.props.children will be an array with two elements. When looped over child.type works only for span to return the string span, what property is there that will give me the string Example for a react element?

If I have a ponent that renders the following:

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

The property this.props.children will be an array with two elements. When looped over child.type works only for span to return the string span, what property is there that will give me the string Example for a react element?

Share Improve this question asked Sep 24, 2015 at 4:14 ThomasReggiThomasReggi 59.7k97 gold badges259 silver badges459 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

If the ponent class has a display name, you should be able to use child.type.displayName. This example demonstrates.

Use this to get the string regardless if it's a native DOM Element or ReactElement.

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

评论列表(0)

  1. 暂无评论