【问题标题】:How to set display name for a React class (ES6)?如何为 React 类(ES6)设置显示名称?
【发布时间】:2020-08-03 05:57:55
【问题描述】:

我已经尝试了几种方法来设置我的 React 组件的显示名称,但没有一个奏效: 我尝试将它设置为这样的公共静态变量:

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

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

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

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

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

我最终得到一个错误提示:

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

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

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

【问题讨论】:

标签: javascript reactjs typescript ecmascript-6


【解决方案1】:

而不是使用public static displayName = "Base";删除公共并像static displayName = "Base";一样使用它

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

【讨论】:

  • eslint 在此更改后给了我两个错误:Missing accessibility modifier on class property displayName @typescript-eslint/explicit-member-accessibilityComponent definition is missing display name react/display-name
  • 禁用.eslintrc文件中的规则
【解决方案2】:

你在用this ESLint plugin我接受吗?

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

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

【讨论】:

【解决方案3】:

在这里回答我自己的问题。事实证明,问题出在与我最初想象的不同的领域。 eslint 错误 Component definition is missing display name react/display-name 指出我使用匿名函数返回 React 组件:

export function renderForm(){
    return {
        react: () => <Base />
    }
}

我以为是说&lt;Base/&gt; 需要一个显示名称,但后来发现问题出在未命名的函数上。我通过命名该函数来解决它:

export function renderForm(){
    return {
        react: function renderComponent(){ return <Base />}
    }
}

不确定这是否对其他人有帮助,但 eslint 错误现在消失了!

编辑:更改规则,如其他两个答案所述,也是一个有效的解决方案,仅供参考

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多