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

Javascript 如何访问this.props.children中React对象的类名,javascript,reactjs,Javascript,Reactjs,在react component render方法中,该方法在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 }) 我认为您需要的是child.\u currentElement.type

在react component render方法中,该方法在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
})

我认为您需要的是
child.\u currentElement.type.displayName
,但我会小心使用这样的内部构件,除非您想再次检查它们在每次升级中是否仍能正常工作。我认为没有一个公共api可以获取组件的名称。

警告:如果使用缩小,这在生产中不起作用

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

import React from 'react'

...

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

    return childClass.name        
}

我使用的实用工具与@Vaclav相同,但如果使用redux connect,您将获得“connect”作为名称,这可能会导致问题。这是我的改进版本:

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

你能提供一些代码示例来说明你的代码中有什么吗?在原始帖子中添加了一些代码。现在还不清楚你想做什么。是否要区分它们以使其样式不同?是否要显示不同的基于数据的数据。如果你需要帮助,你需要问一个精确的问题。问题是我怎样才能得到孩子的类名或其他标识符?根据组件类的不同,子级将具有不同的属性。感谢您,我不知道。答案已过时,请使用
child.type.name
获取
函数。name
对此保持关注。当您使用npm run build为生产构建项目时,
子.type.name
将不相同!例如:如果您检查名称props是否等于某个值<代码>如果(child.type.name==='componentName')这在生产模式下不起作用