reactjs - What is the correct way to type a React HOC?
问题描述
I'm trying to figure out if I am typing my react Higher order component correctly. For the most part this is working correctly, however I'm running into a typing issue when applying a React reference to an instance of the HOC. Below is a simplified repro:
import * as React from "react";
// Is returning a React.ComponentClass correct here?
function HOC(): (Component: React.ComponentType) => React.ComponentClass {
return function(Component: React.ComponentType): React.ComponentClass {
return class Bar extends React.Component {}
}
}
class Foo extends React.Component<{},{}> {}
const Bar = HOC()(Foo);
class Test extends React.Component {
private ref: React.RefObject<typeof Bar> = React.createRef<typeof Bar>();
render(): any {
return (
<React.Fragment>
<Bar
ref={this.ref} // error here
/>
</React.Fragment>
);
}
}
I've also capture the issue here: https://stackblitz.com/edit/react-ts-rtmfwr
The error I'm getting is:
index.tsx:20:21 - error TS2322: Type 'RefObject<ComponentClass<{}, any>>' is not assignable to type 'Ref<Component<{}, any, any>>'.
Type 'RefObject<ComponentClass<{}, any>>' is not assignable to type 'RefObject<Component<{}, any, any>>'.
Type 'ComponentClass<{}, any>' is not assignable to type 'Component<{}, any, any>'.
Property 'setState' is missing in type 'ComponentClass<{}, any>'.
解决方案
This should work:
import * as React from "react";
// In a more realistic example, there would be a more interesting relationship
// between the props types of the wrapped and resulting components.
function HOC(): <P>(Component: React.ComponentType<P>) => React.ComponentClass<{}> {
return function<P>(Component: React.ComponentType<P>): React.ComponentClass<{}> {
return class Bar extends React.Component<{}> {}
}
}
class Foo extends React.Component<{x: string},{}> {}
const Bar = HOC()(Foo);
// Get the instance type corresponding to the `Bar` constructor function,
// as you would have if you had just written `class Bar`.
type Bar = InstanceType<typeof Bar>;
class Test extends React.Component {
private ref: React.RefObject<Bar> = React.createRef<Bar>();
render(): any {
return (
<React.Fragment>
<Bar
ref={this.ref}
/>
</React.Fragment>
);
}
}
推荐阅读
- c - 互斥锁已经被我锁定了吗?
- php - 自定义查询中的日期在 Wordpress 中无法正确显示
- authentication - reSolve 框架:如何通过 HTTP 请求(routeRegisterCallback)对用户进行身份验证?
- android - Android中没有角的圆形按钮
- java - 在 JOOQ 中使用 RecordMapper 将派生列映射到 POJO
- string - 字符串操作在 tcsh 中不起作用 - 不理解子程序的变量
- swift - 如何在 Swift 中获取本地化的文件大小单位
- webserver - 如何使用 sd 卡托管 html
- python - 合并对设置为列表
- java - 如何在按下按钮时动态添加和删除多个 EditText 字段?