我正在按照本教程使用React.forwardRef,在哪里制作此组件:
import React from "react";
const Search = React.forwardRef<HTMLInputElement>((props, ref) => {
return <input ref={ref} type="search" />;
});
export default Search;
Run Code Online (Sandbox Code Playgroud)
但是,运行我的应用程序时,该组件会导致以下错误:
Component definition is missing display name react/display-name
Run Code Online (Sandbox Code Playgroud)
基于这个问题,我想我可能会做这样的事情:
Component definition is missing display name react/display-name
Run Code Online (Sandbox Code Playgroud)
但这也没有解决问题。
那么,我怎样才能给我的组件一个显示名称呢?
Fro*_*ost 217
该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
从该页面中,您还可以找到它存在的原因displayName以及React 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;
Run Code Online (Sandbox Code Playgroud)
// eslint-disable-next-line react/display-name另一种选择是仅禁用该特定的 linter,使用组件声明上方的注释或类似注释。
然而,这意味着如果您需要调试您的应用程序,只需调用此组件input而不是Search,这可能会使调试变得更加困难。
A. *_*son 53
我最近遇到了同样的问题并通过这种方式解决了。可能不是最漂亮的,但可能是某些人的首选。ComponentNameReact 名称在哪里,ExportName是您将在其他地方导入的名称。
const ComponentName = (props, ref) => {
return (
<div ref={ref}></div>
);
};
export const ExportName = forwardRef(ComponentName);
Run Code Online (Sandbox Code Playgroud)
Ser*_*ure 35
您可以使用命名函数(请参阅 参考资料function Search)来代替匿名箭头 fn,如下面的示例所示。
const Search = React.forwardRef<HTMLInputElement>(function Search(props, ref) {
return <input ref={ref} type="search" />;
});
export default Search;
Run Code Online (Sandbox Code Playgroud)
小智 17
import React from "react";
const Search = React.forwardRef<HTMLInputElement>(function Search(props, ref) {
return <input ref={ref} type="search" />;
});
export default Search;
Run Code Online (Sandbox Code Playgroud)
这样就可以解决问题了。我建议我们最好知道为什么eslint限制书写方式
Dav*_*'G' 15
除了拉尔森的回应(我认为这是可行的方法)之外,如果您仍然想进行打字,您可以执行以下操作:
import { forwardRef, ForwardRefRenderFunction } from "react";
type MyComponentProps = {
something: string;
}
type RefProps = {
something: string;
}
const MyComponent: ForwardRefRenderFunction<RefProps, MyComponentProps> = (props, ref) => {
return <div>Works</div>;
}
export default forwardRef(MyComponent);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71664 次 |
| 最近记录: |