组件定义缺少forwardRef的显示名称

2023-12-19

我正在关注本教程 https://www.carlrippon.com/react-forwardref-typescript/关于使用React.forwardRef,在哪里制作这个组件:

import React from "react";

const Search = React.forwardRef<HTMLInputElement>((props, ref) => {
  return <input ref={ref} type="search" />;
});

export default Search;

但是,运行我的应用程序时,该组件会导致以下错误:

Component definition is missing display name  react/display-name

Based 关于这个问题 https://stackoverflow.com/questions/54602013/component-definition-is-missing-display-name-on-hoc,我想我可能会做这样的事情:

const Search = MySearch = React.forwardRef<HTMLInputElement>((props, ref) => {
  return <input ref={ref} type="search" />;
});

export default Search;

但这也没有解决问题。

那么,我怎样才能给我的组件一个显示名称呢?


The Component definition is missing display name react/display-name消息可能来自 eslint 这样的工具。

这是一个 linting 规则,旨在帮助您在编写 React 代码时遵循有关良好实践的风格指南和/或约定。

eslint 中的特定规则在这里有更详细的解释:https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/display-name.md

从该页面您还可以找到why它存在并且是什么displayNameReact Components 上的属性很有用,即在调试时提供帮助,因为这意味着它将打印组件的displayName属性到控制台而不是仅仅input.

另外,从该链接中,您可以发现当您使用函数组件时,您可以通过设置来解决这个问题displayName组件上的属性。这可能应该对您有帮助:

import React from "react";

const Search = React.forwardRef<HTMLInputElement>((props, ref) => {
  return <input ref={ref} type="search" />;
});
Search.displayName = "Search";

export default Search;

另一种选择是使用注释来禁用特定的 linter// eslint-disable-next-line react/display-name或类似的组件声明上方。

然而,这意味着如果您需要调试您的应用程序,只需调用该组件即可input代替Search,这可能会使调试变得更加困难。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

组件定义缺少forwardRef的显示名称 的相关文章

随机推荐