React 无状态组件的 TypeScript 返回类型是什么?

新手上路,请多包涵

这里的返回类型是什么?

 const Foo
  : () => // ???
  = () => (
    <div>
      Foobar
    </div>
  )

原文由 ahstro 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 426
2 个回答

StatelessComponent 这个答案 中提到的类型已被弃用,因为在引入 Hooks API 后,它们并不总是无状态的。

函数组件的类型为 React.FunctionComponent 并且它有一个别名 React.FC 以保持简洁。

它有一个必需的属性,一个函数,它将返回一个 ReactElementnull 。它有一些可选属性,例如 propTypescontextTypesdefaultPropsdisplayName

这是一个例子:

 const MyFunctionComponent: React.FC = (): ReactElement => {
  return <div>Hello, I am a function component</div>
}

以下是来自@types/react 16.8.24 的类型:

 type FC<P = {}> = FunctionComponent<P>;

interface FunctionComponent<P = {}> {
    (props: PropsWithChildren<P>, context?: any): ReactElement | null;
    propTypes?: WeakValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
}

原文由 Timo 发布,翻译遵循 CC BY-SA 4.0 许可协议

interface ISomeCoolInterface {
   some: 'string';
   cool: 'string';
   props: 'string'
}

const SomeCoolComponent
    : React.FC<ISomeCoolInterface>
    = ({ some, cool, props }): JSX.Element => {
        return <SomeCoolComponent>{some, cool, props}</SomeCoolComponent>
    }

这里重要的一点是返回类型 JSX.Element

原文由 Vishal Sakaria 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进