如何在功能组件中设置 displayName [React] [英] how to set displayName in a functional component [React]

查看:23
本文介绍了如何在功能组件中设置 displayName [React]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有时需要设置 displayName,尤其是在处理生产版本时.我想知道如何使用我的功能组件设置它 - 是否可能/允许?

I know that setting the displayName is sometimes required especially when you're dealing with production builds. I want to know how to set it using my functional component - is it possible/allowed?

这是我的类组件中的内容:

Here's what I've got in my class component:

const MyComponent = React.createClass({
  displayName: 'HeyHey',

  render: function() {
    console.log(this.displayName);
  }
});

如何在无状态组件中做同样的事情?

How do I do the same thing inside a stateless component?

推荐答案

<代码>显示名称

displayName 字符串用于调试消息.通常,您不需要显式设置它,因为它是从定义组件的函数或类的名称中推断出来的.如果您想为调试目的或创建高阶组件时显示不同的名称,您可能需要明确设置它,请参阅 包装显示名称以方便调试以了解详细信息.

The displayName string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component, see Wrap the Display Name for Easy Debugging for details.

在您的情况下,您只需使用

In your case, you would simply use

const MyComponent = (props) => { ... }

MyComponent.displayName = 'HeyHey'


或者你可以使用Object.assign

const MyComponent =
  Object.assign
    ( props => { ... }
    , { displayName: 'HeyHey' }
    )

这篇关于如何在功能组件中设置 displayName [React]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆