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

查看:154
本文介绍了如何在功能组件中设置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:

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

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

如何在无状态组件中执行相同的操作?

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

推荐答案

displayName


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

The displayNamestring 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'






如果您要在组件上设置默认属性,请使用 defaultProps 而不是

const MyComponent = props => {
  return (
    <p>How you doin, {props.name}?</p>
  )
}

MyComponent.defaultProps = {
  name: 'Alice'
}

ReactDOM.render (<MyComponent/>, document.body)
// <p>How you doin, Alice?</p>

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

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