gpt4 book ai didi

reactjs - 如何创建接受泛型的无状态功能组件?

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:36 25 4
gpt4 key购买 nike

Typescript 泛型可用于扩展接口(interface)。

interface Sample1<P> {
prop1: P;
}

interface Sample2<P> extends Sample1<P> {
prop2: string;
}

但是当我尝试创建一个使用通用接口(interface)的功能组件时, typescript 会抛出错误。

const SampleSFC: React.SFC<Sample2<P>> = () => <div />;

error TS2304: Cannot find name 'P'.

如果我替换 P使用已知类型,如 string错误消失了。

const SampleSFC: React.SFC<Sample2<string>> = () => <div />;

而不是 P 的硬编码类型,这完全扼杀了泛型的目的,我想启用 SampleSFC 的用户设置 P 的类型.

我该怎么做?如果不可能,那么我应该遵循什么样的替代设计,让我拥有带有通用 Prop 的 SFC。

最佳答案

通用类型变量可以在函数和类型声明中使用,就像您的接口(interface)一样Sample1Sample2 .但是当您实际使用/调用/调用 泛型类型时,您必须指定一个具体 类型参数而不是 P .

React.SFC - 无状态函数组件类型 - 是一个接口(interface)声明,因此在 const 中使用它P 赋值需要具体类型.

我想到的唯一解决方案是制作 SFC看起来像function ts-compiler 的类型,因为函数声明/表达式可以被分配泛型类型参数。参见 Typescript docs举一些例子。

通用证监会声明

省略 React.SFC为您的作业键入注释 const SampleSFC :

const SampleSFC = <P extends {}>(props: Sample2<P>) => <div>{props.prop1} </div>;

Note: The <P extends {}> part is needed due to JSX/TSX compatibility issues with generics, see the end of this post.

这样,您的组件仍然是一个普通函数。如果您需要来自 React.SFC 的其他成员,将它们添加到您的 Prop 中。例如。如果children需要:

const SampleSFC = <P extends {}>(props: Sample2<P> & { children?: ReactNode })
=> <div >{props.prop1} </div>;

一般 SFC 用法

Typescript 2.9 ,类型参数可以直接在JSX中设置。

const MyApp: React.SFC<{}> = (props) => {
return <SampleSFC<number> prop2="myString" prop1={1} />
}

备选方案

1.) 如果您不喜欢这种怪癖,那么切换到类组件会很容易。

class SampleSFCClass<P> extends React.Component<Sample2<P>> {
render() {
return <div>{this.props.prop1}</div>
}
}

const MyApp2: React.SFC<{}> = (props) => {
return <SampleSFCClass<number> prop2="myString" prop1={1} />
}

2.) 你甚至可以包装 SFC在另一个函数中。

const withGeneric: <P>() => React.SFC<Sample2<P>> = <P extends {}>() => {
return (props) => <div> {props.prop1} {props.prop2} </div>;
}

const SampleSFCCalled: React.SFC<Sample2<string>> = withGeneric<string>();

const MyApp: React.SFC<{}> = (props) => {
return <SampleSFCCalled prop2="myString" prop1="aString" />
}

它会工作,但缺点可能是性能略有下降,因为 SFC函数总是在父组件的每个渲染周期中重新创建。

JSX/TSX 与泛型的兼容性问题:

在某些情况下,由于语法不明确,Typescript 似乎无法结合 JSX/TSX(最新的 3.0.1)解析泛型。编译错误将是:

"JSX element has no corresponding closing tag."

建议使用 function 的贡献者之一这种情况下的语法(参见 issue )。

当你坚持使用箭头函数时,解决方法是让类型参数从对象扩展(显示 herehere )以阐明它是一个通用的 lambda 而不是 JSX 标签:

<P extends {}><P extends object>

希望对您有所帮助。

关于reactjs - 如何创建接受泛型的无状态功能组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47848828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com