首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在TypeScript中正确键入泛型React函数组件

如何在TypeScript中正确键入泛型React函数组件
EN

Stack Overflow用户
提问于 2021-05-06 15:09:55
回答 2查看 589关注 0票数 0

在下面的TypeScript Playground示例中,我试图将函数组件Element概括为GenericElement组件,但TypeScript抱怨语法不正确。

如何使用React.FC类型定义方法在TypeScript中正确键入泛型react函数组件?

代码语言:javascript
复制
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>;
};
代码语言:javascript
复制
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.
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-05-07 02:43:05

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

代码语言:javascript
复制
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');
);
票数 0
EN

Stack Overflow用户

发布于 2021-05-06 15:51:08

我认为它使用高阶函数是可行的:

代码语言:javascript
复制
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>>

缺点:仅由于类型而有函数开销

我不相信我的答案是有帮助的,因为你应该显式定义泛型类型,或者你需要传递一个参数来推断它:

代码语言:javascript
复制
const HoC = <T,>(a:T): FC<GenericPropsType<T>> => (props) => <div></div>

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67413371

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档