如何在this.props.children中访问React对象的类名

时间:2015-01-29 15:47:05

标签: javascript reactjs

在一个反应​​组件渲染方法中,在this.props.children中有一些子组件。如何获取每个孩子的组件(类)名称以区分它们?

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

3 个答案:

答案 0 :(得分:6)

在ES6中,每个函数的名称都存储在属性function.name中,因此您可以使用

获取类名
import React from 'react'

...

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

    return childClass.name        
}

我正在使用React.children实用程序

警告:如果使用缩小功能,则无法在生产中使用

答案 1 :(得分:0)

我认为你想要的是child._currentElement.type.displayName但是我会小心使用这样的内部,除非你想要仔细检查它们在每次升级中是否仍能正常运行。我不认为有一个公共api来获取组件的名称。

答案 2 :(得分:0)

和@Vaclav一样,但是如果你使用redux connect,你将获得" Connect"作为可能导致问题的名称。这是我的改进版本:

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