最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set displayName in class based component? - Stack Overflow

programmeradmin3浏览0评论

I'm trying to set the displayName property of this class that extends React.Component. The React docs say that displayName is a property, so it possible to set it in the constructor? Here's what I'm trying:

class TestUI extends React.Component {
   constructor(){
     this.displayName = 'CustomTestUI'
   }
}

But the library I'm using (pao) isn't picking it up. Am I setting it incorrectly? I've also tried setting it outside the class like stateless ponents MyClass.displayName = 'Test' which also doesn't have an effect.

Edit: The answer is: static displayName = 'CustomTestUI'

I'm trying to set the displayName property of this class that extends React.Component. The React docs say that displayName is a property, so it possible to set it in the constructor? Here's what I'm trying:

class TestUI extends React.Component {
   constructor(){
     this.displayName = 'CustomTestUI'
   }
}

But the library I'm using (pao) isn't picking it up. Am I setting it incorrectly? I've also tried setting it outside the class like stateless ponents MyClass.displayName = 'Test' which also doesn't have an effect.

Edit: The answer is: static displayName = 'CustomTestUI'

Share Improve this question edited Aug 23, 2017 at 14:35 a53-416 asked Aug 23, 2017 at 3:08 a53-416a53-416 3,9956 gold badges36 silver badges47 bronze badges 1
  • 5 have you tried static displayName = 'yourName'? – Dayan Moreno Leon Commented Aug 23, 2017 at 4:42
Add a ment  | 

2 Answers 2

Reset to default 4

As stated in the ments, displayName should be set on the class as a static variable and not an instance using this.

class TestUI extends React.Component {
   static displayName = 'CustomTestUI';
   ...
}

Here are a couple of examples of where React retrieves displayName from the ponent class in this error and this function.

You can also set the displayName of a ponent via Component.displayName = 'myName'.

class TestUI extends React.Component {
    ...
}

TestUI.displayName = 'CustomTestUI';

The ments and answers given should suffice, however I thought it a good opportunity to describe why your initial attempt did not work (and why it would have been a bad idea anyways).

When working with classes, you have the class "constructor" which is used to create many class "instances". Inside your class methods, all references to this refer to the class instance. You can always access the constructor by doing this.constructor.

So the following would have worked, though it is very bad practice for an instance to change a property on its constructor - DO NOT DO THIS:

class TestUI extends React.Component {
   constructor(){
     // DO NOT DO THIS (for educational purposes only - see other answers)
     this.constructor.displayName = 'CustomTestUI'
   }
}
发布评论

评论列表(0)

  1. 暂无评论