admin管理员组

文章数量:1401622

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
}

本文标签: javascriptGet react element string typeStack Overflow