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

javascript - How to access the class name of a React object in this.props.children - Stack Overflow

programmeradmin12浏览0评论

In a react component render method that has some children components in this.props.children. How can I get the component (class) name of each child to differentiate between them?

React.Children.map(this.props.children, function(child){
    // how can I get the class name of a child or some other identifier
})

In a react component render method that has some children components in this.props.children. How can I get the component (class) name of each child to differentiate between them?

React.Children.map(this.props.children, function(child){
    // how can I get the class name of a child or some other identifier
})
Share Improve this question edited Mar 27, 2015 at 15:24 James Montagne 78.7k14 gold badges114 silver badges132 bronze badges asked Jan 29, 2015 at 15:47 CodewithcheeseCodewithcheese 3001 gold badge3 silver badges9 bronze badges 4
  • Could you provide some code examples presenting what you have in your code? – daniula Commented Jan 29, 2015 at 16:38
  • Added some code to original post – Codewithcheese Commented Jan 29, 2015 at 16:54
  • It's still unclear what you are trying to do. Do you want to differentiate between them to style them differently? Do you want to display different data based. If you need help you need to ask precise question. – daniula Commented Jan 29, 2015 at 16:56
  • 1 The question is how can I get the class name of a child or some other identifier? The children will have different properties depending on what component class it is. – Codewithcheese Commented Jan 29, 2015 at 17:02
Add a comment  | 

3 Answers 3

Reset to default 9

Warning: this will not work in production if using minification

In ES6 every function has its name stored in property function.name so you can get Class name with

import React from 'react'

...

getNameOfChildrenClass() {
    const singleChild = React.children.only(this.props.children),
          childClass = child.type

    return childClass.name        
}

I'm using React.children utility

The same as @Vaclav, but if you are using redux connect you will get "Connect" as name which may cause problems. Here is my improved version:

let{ name, displayName=name } = child.type;
React.cloneElement(child, {
  ...
  key:displayName,
});

I think what you want is child._currentElement.type.displayName but I would be careful about using internals like this, unless you want to double check they still function correctly in every upgrade. I don't think there is a public api for getting the name of a component.

发布评论

评论列表(0)

  1. 暂无评论