如何在 this.props.children 中访问 React 对象的 class 名称
How to access the class name of a React object in this.props.children
在 this.props.children 中有一些子组件的 React 组件渲染方法中。如何获取每个子项的组件 (class) 名称以区分它们?
React.Children.map(this.props.children, function(child){
// how can I get the class name of a child or some other identifier
})
我想你想要的是 child._currentElement.type.displayName
但我会小心使用这样的内部结构,除非你想仔细检查它们在每次升级时是否仍然正常运行。我认为没有用于获取组件名称的 public api。
警告:如果使用缩小
,这将无法在生产中使用
在 ES6 中,每个函数的名称都存储在 属性 function.name
中,因此您可以使用
获得 Class 名称
import React from 'react'
...
getNameOfChildrenClass() {
const singleChild = React.children.only(this.props.children),
childClass = child.type
return childClass.name
}
我正在使用 React.children
实用程序
与@Vaclav 相同,但如果您使用的是 redux connect,您将获得 "Connect" 作为名称,这可能会导致问题。这是我的改进版本:
let{ name, displayName=name } = child.type;
React.cloneElement(child, {
...
key:displayName,
});
在 this.props.children 中有一些子组件的 React 组件渲染方法中。如何获取每个子项的组件 (class) 名称以区分它们?
React.Children.map(this.props.children, function(child){
// how can I get the class name of a child or some other identifier
})
我想你想要的是 child._currentElement.type.displayName
但我会小心使用这样的内部结构,除非你想仔细检查它们在每次升级时是否仍然正常运行。我认为没有用于获取组件名称的 public api。
警告:如果使用缩小
,这将无法在生产中使用在 ES6 中,每个函数的名称都存储在 属性 function.name
中,因此您可以使用
import React from 'react'
...
getNameOfChildrenClass() {
const singleChild = React.children.only(this.props.children),
childClass = child.type
return childClass.name
}
我正在使用 React.children
实用程序
与@Vaclav 相同,但如果您使用的是 redux connect,您将获得 "Connect" 作为名称,这可能会导致问题。这是我的改进版本:
let{ name, displayName=name } = child.type;
React.cloneElement(child, {
...
key:displayName,
});