繁体   English   中英

如何在 TypeScript 中正确键入通用 React function 组件

[英]How to correctly type a generic React function component in TypeScript

在下面的TypeScript Playground示例中,我尝试将 function 组件Element概括为GenericElement组件,但 TypeScript 抱怨语法。

如何使用React.FC类型定义方法在 TypeScript 中正确键入通用反应 function 组件?

import React from 'react';

type PropsType = {
  id: string,
  value: string,
};

type GenericPropsType<keyType> = {
  id: keyType,
  value: string,
};

const Element: React.FC<PropsType> = ({ id, value }) => {
  return <div>{id.toString()}={value}</div>;
};

const GenericElement: React.FC<GenericPropsType<keyType>> = <keyType = string>({ id, value }) => {
  return <div>{id.toString()}={value}</div>;
};
Type 'Element' is not assignable to type 'FC<GenericPropsType<any>>'.
Type 'Element' provides no match for the signature '(props: PropsWithChildren<GenericPropsType<any>>, context?: any): ReactElement<any, any> | null'.
Cannot find name 'keyType'.
Property 'keyType' does not exist on type 'JSX.IntrinsicElements'.
Cannot find name 'id'.
Left side of comma operator is unused and has no side effects.
Cannot find name 'value'.
Cannot find name 'id'.
Cannot find name 'value'.
Identifier expected.
Unexpected token. Did you mean `{'>'}` or `&gt;`?
Expression expected.
Unexpected token. Did you mean `{'}'}` or `&rbrace;`?
JSX element 'keyType' has no corresponding closing tag.
'</' expected.
'Element' is declared but its value is never read.

我认为它可以使用高阶 function:

import React, { FC } from 'react';

type GenericPropsType<T = any> = {
  id: T,
  value: string,
};

const HoC = <T,>(): FC<GenericPropsType<T>> => (props) => <div></div>

const WithString = HoC<string>() // React.FC<GenericPropsType<string>>

缺点:你有 function 开销只是因为类型

我不相信我的回答有帮助,因为您应该明确定义泛型类型,或者您需要传递一个参数才能推断它:

const HoC = <T,>(a:T): FC<GenericPropsType<T>> => (props) => <div></div>

const WithString = HoC('a') // React.FC<GenericPropsType<string>>

否则,我建议您使用@Aleksey L.的解决方案。

根据@Aleksey L. 的解释,我得出了以下可能对其他人有帮助的完整示例:

import React from 'react';
import ReactDOM from 'react-dom';

type GenericPropsType<keyType> = {
  id: keyType,
  value: string,
};

const GenericElement = <keyType extends string | number = string>({
  id,
  value = ''
}: GenericPropsType<keyType>): JSX.Element => {
  return (<div>{id}={value}</div>);
};

const UseGenericElement: React.FC = () => {
  return (<div><GenericElement id={4711} value="4711" /></div>);
};

ReactDOM.render(
  <div><UseGenericElement /></div>,
  document.getElementById('root');
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM