gpt4 book ai didi

reactjs - 使用 TypeScript 为 React 高阶组件输入注解

转载 作者:搜寻专家 更新时间:2023-10-30 20:37:53 26 4
gpt4 key购买 nike

我正在使用 Typescript 为我的 React 项目编写一个高阶组件,它基本上是一个接受 React 组件作为参数并返回一个环绕它的新组件的函数。

然而,正如预期的那样,TS 提示“导出函数的返回类型具有或正在使用私有(private)名称“匿名类”。

有问题的功能:

export default function wrapperFunc <Props, State> (
WrappedComponent: typeof React.Component,
) {
return class extends React.Component<Props & State, {}> {
public render() {
return <WrappedComponent {...this.props} {...this.state} />;
}
};
}

这个错误是合理的,因为包装函数的返回类没有导出,其他模块导入这个函数无法知道返回值是什么。但是我不能在此函数之外声明返回类,因为它需要将组件传递给外部函数。

像下面这样显式指定返回类型 typeof React.Component 的试验会抑制此错误。

具有显式返回类型的问题函数:

export default function wrapperFunc <Props, State> (
WrappedComponent: typeof React.Component,
): typeof React.Component { // <== Added this
return class extends React.Component<Props & State, {}> {
public render() {
return <WrappedComponent {...this.props} {...this.state} />;
}
};
}

但是,我不确定这种方法的有效性。它是否被认为是解决 TypeScript 中这个特定错误的正确方法? (或者我是否在其他地方产生了意想不到的副作用?或者有更好的方法吗?)

(编辑)根据 Daniel 的建议更改引用的代码。

最佳答案

Type annotation for React Higher Order Component using TypeScript

返回类型 typeof React.Component 是真实的,但对包装组件的用户不是很有帮助。它会丢弃有关组件接受哪些 props 的信息。

React 类型为此目的提供了一个方便的类型,React.ComponentClass。它是类的类型,而不是从该类创建的组件的类型:

React.ComponentClass<Props>

(请注意,未提及 state 类型,因为它是内部细节)。

在你的情况下:

export default function wrapperFunc <Props, State, CompState> (
WrappedComponent: typeof React.Component,
): React.ComponentClass<Props & State> {
return class extends React.Component<Props & State, CompState> {
public render() {
return <WrappedComponent {...this.props} {...this.state} />;
}
};
}

但是,您正在使用 WrappedComponent 参数做同样的事情。根据您在 render 中使用它的方式,我猜它也应该被声明:

WrappedComponent: React.ComponentClass<Props & State>,

但这是大胆的猜测,因为我认为这不是完整的函数(未使用 CompState,并且 Props & State 也可能是单个类型参数因为它总是出现在那个组合中)。

关于reactjs - 使用 TypeScript 为 React 高阶组件输入注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41499831/

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