[英]How to access the class name of a React object in this.props.children
In a react component render method that has some children components in this.props.children.在 this.props.children 中有一些子组件的 react 组件渲染方法中。 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
})
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在 ES6 中,每个函数的名称都存储在属性
function.name
因此您可以使用
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我正在使用
React.children
实用程序
The same as @Vaclav, but if you are using redux connect you will get "Connect" as name which may cause problems.与@Vaclav 相同,但如果您使用的是 redux connect,您将获得“Connect”作为名称,这可能会导致问题。 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.我认为你想要的是
child._currentElement.type.displayName
但我会小心使用这样的内部结构,除非你想仔细检查它们在每次升级中是否仍然正常工作。 I don't think there is a public api for getting the name of a component.我认为没有用于获取组件名称的公共 api。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.