Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

javascript - how to set displayName in a functional component [React]

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?

question from:https://stackoverflow.com/questions/43356073/how-to-set-displayname-in-a-functional-component-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The docs for displayName say

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'

Or you can use Object.assign

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...