Javascript 如何在功能组件中设置 displayName [React]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43356073/
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-08-23 01:51:21  来源:igfitidea点击:

how to set displayName in a functional component [React]

javascriptreactjsfunctional-programming

提问by a53-416

I know that setting the displayNameis 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?

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

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?

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

回答by Thank you

The docs for displayNamesay

文档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.

displayName字符串用于调试消息。通常,您不需要显式设置它,因为它是从定义组件的函数或类的名称推断出来的。如果您想为调试目的显示不同的名称或创建高阶组件时,您可能需要显式设置它,请参阅Wrap the Display Name for Easy Debugging 了解详细信息

In your case, you would simply use

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

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

MyComponent.displayName = 'HeyHey'


If you're looking to set default properties on a component, use defaultPropsinstead

如果您想在组件上设置默认属性,请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>

回答by a53-416

Figured it out

弄清楚了

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

MyComponent.displayName = "MyComponent"