React 中 Component definition is missing display name 错误

在组件上设置 displayName 属性以修复“Component definition is missing display name”错误,例如 App.displayName = 'MyApp';。 或者,禁用带有以下注释的行的 ESLint 规则 – // eslint-disable-next-line react/display-name

const App = () => {
  return (
    <div>
      <h2>Hello world</h2>
    </div>
  );
};

// 👇️ set display name
App.displayName = 'MyApp';

export default App;

该错误通常是在 React 中使用 forwardRefs 时导致的。

displayName 属性用于为 React devtools 扩展的组件提供一个描述性名称。

或者,我们可以通过在 ESlint 错误发生的正上方放置注释来禁用单行的 ESlint 规则。

// eslint-disable-next-line react/display-name
const App = () => {
  return (
    <div>
      <h2>Hello world</h2>
    </div>
  );
};

export default App;

该注释将禁用单行规则。

或者,我们可以通过将属性添加到 .eslintrc.js 文件的规则对象来禁用整个项目的 react/display-name 规则。

module.exports = {
  rules: {
    "react/display-name": "off",
  }
}

我们还可以通过在文件顶部添加以下注释来禁用单个文件的规则。

/* eslint-disable react/display-name */

// ... your code here

总结

在组件上设置 displayName 属性以修复“Component definition is missing display name”错误,例如 App.displayName = 'MyApp';。 或者,禁用带有以下注释的行的 ESLint 规则 – // eslint-disable-next-line react/display-name