如何使用泛型 props 将功能组件声明为常量

How to declare functional component with generic props as a constant

提问人:Marcus Junius Brutus 提问时间:9/28/2023 最后编辑:jonrsharpeMarcus Junius Brutus 更新时间:10/7/2023 访问量:35

问:

这是你如何定义一个在其 props 中接受泛型类型的 React 组件:

type Props<T> {
  data: T;
}

export const MyComponent = <T,>(props: Props<T>) => {
  return (
  <div>whatever</div>;
  )
};

如果我进一步希望声明 MyComponent 功能组件的类型,我将如何使用?React.FC

以下操作失败,并显示:Cannot find type T

export const MyComponent : React.FC<OwnProps<T>> = <T,>(props: OwnProps<T>) => {

我知道如何做到这一点,我的问题是我是否可以使用成语添加此类型信息。export function MyComponentexport const MyComponent

reactjs typescript react-functional-component

评论

2赞 merryweather 9/28/2023
你就是做不到。
1赞 merryweather 9/28/2023
有传言说“React.FC 被弃用”,但 AFAIK 没有官方通知。无论如何,单击链接的任何谷歌搜索结果,看看为什么 React.FC 很糟糕,应该避免。

答:

-2赞 Kyra Bradley 9/29/2023 #1

export const MyComponent: React.FC<Prop T> = ({ data }) => {}

  • 尖括号内是接口类型
  • data 将是传递给组件的 props