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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28218814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:37:38  来源:igfitidea点击:

How to access the class name of a React object in this.props.children

javascriptreactjs

提问by Codewithcheese

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?

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

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

采纳答案by Stuart Leigh

I think what you want is child._currentElement.type.displayNamebut 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.

我想你想要的是child._currentElement.type.displayName但我会小心使用这样的内部结构,除非你想仔细检查它们在每次升级中是否仍然正常工作。我认为没有用于获取组件名称的公共 api。

回答by Vaclav Novotny

In ES6 every function has its name stored in property function.nameso 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.childrenutility

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

Warning: this will not work in production if using minification

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

回答by Jin Tim

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:

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

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