如何为 React 类(ES6)设置显示名称?

avh*_*hhh 5 javascript typescript ecmascript-6 reactjs

我已经尝试了几种方法来为我的 React 组件设置显示名称,但都没有奏效:我尝试将其设置为公共静态变量,如下所示:

class Base extends React.Component<any, any>{
    public static displayName = "Base";
    constructor(props){
        ...
    }
    render(){
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

但是 eslint 仍然给我抛出这个错误:

error Component definition is missing display name react/display-name

我尝试了另一种方法,将它设置在类定义之外:

class Base extends React.Component<any, any>{
    constructor(props){
        ...
    }
    render(){
        ...
    }
}
Base.displayName = "Base";
Run Code Online (Sandbox Code Playgroud)

我最终收到一条错误消息:

Property 'displayName' does not exist on type 'typeof Base'.

我尝试了与其他 Stackoverflow 帖子不同的方法,但似乎无法摆脱错误。我该如何解决这个问题?请帮忙。

编辑:在下面回答了我自己的问题。这个问题的核心似乎是关于匿名函数而不是 React 类。

Jag*_*ati 5

而不是使用public static displayName = "Base";remove public 并像使用它一样使用它static displayName = "Base";

class Base extends React.Component<any, any>{
    static displayName = "Base";
    constructor(props){
        ...
    }
    render(){
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*man 0

你正在使用这个 ESLint 插件吗?

在这种情况下,您是否将ignoreTranspilerName选项设置为true?如果是这样,那可能是你的问题。

如果您已经有了组件的名称,为什么还要制定这条规则呢?转译器默认应使用类名作为组件名