gpt4 book ai didi

reactjs - React HOC 作为类组件有 Typescript 错误,但作为函数组件没有

转载 作者:行者123 更新时间:2023-12-05 06:52:23 25 4
gpt4 key购买 nike

typescript - v3.9.7

我有一个 HOC,可以将额外的 props 传递给组件:

import React from 'react';

interface IWithOwner {
owner: string;
}

type IWithoutOwner<T extends IWithOwner> = Omit<T, keyof IWithOwner> & {owner?: never};

// CORRECT
export function withOwnerOne<TProps extends IWithOwner>(Component: React.ComponentType<TProps>) {
const ComponentWithOwner: React.FunctionComponent<IWithoutOwner<TProps>> = (props) => {
return (
<Component
owner="Tom"
{...props}
/>
);
}

return ComponentWithOwner;
}

// ERROR
export function withOwnerTwo<TProps extends IWithOwner>(Component: React.ComponentType<TProps>) {
return class extends React.Component<IWithoutOwner<TProps>> {
render() {
return (
// '{ owner: string; } & Readonly<IWithoutOwner<TProps>> & Readonly<{ children?: ReactNode; }>'
// is assignable to the constraint of type 'TProps', but 'TProps' could be
// instantiated with a different subtype of constraint 'IWithOwner'.
<Component
owner="Tom"
{...this.props}
/>
)
}
}
}
使用 Function 组件的

withOwnerOne 可以正常工作。而使用class组件的withOwnerTwo有错误。为什么它们的工作方式不同?

Playground link

Same case with functions works correctly

最佳答案

我认为问题出在 props类型。

在第一个例子中,FunctionComponent ,类型 props是:IWithoutOwner<TProps> & { children?: ReactNode };

interface IWithOwner {
owner: string;
}

type IWithoutOwner<T extends IWithOwner> = Omit<T, keyof IWithOwner> & {
owner?: never;
};

function withOwnerTwo<TProps extends IWithOwner>(
Component: React.ComponentType<TProps>
) {
const ComponentWithOwner: React.FunctionComponent<IWithoutOwner<TProps>> = (
props
) => {

// React.PropsWithChildren<IWithoutOwner<TProps>> --> IWithoutOwner<TProps> & { children?: ReactNode };
const x = props;
return <Component owner="Dmitry" {...props} />;
};

return ComponentWithOwner;
}

第二,props有一点不同的类型:

Readonly<IWithoutOwner<TProps>> & Readonly<{children?: React.ReactNode;}>

function withOwnerOne<TProps extends IWithOwner>(
Component: React.ComponentType<TProps>
) {
class Wrapper extends React.Component<IWithoutOwner<TProps>> {
render() {
//Readonly<IWithoutOwner<TProps>> & Readonly<{children?: React.ReactNode;}>
const props = this.props;

return <Component owner="Dmitry" {...props} />;
}
}

return Wrapper;
}

现在,您可能认为问题出在Readonly 中。修饰符。 Readonly不会导致错误。我坚信,该错误是由逆变引起的。

因为 props 的类型取自组件上下文,props generic 放置在上述组件的不同位置。

我乐于接受批评,请随时指出我的错误。

Covariance/variance/invariance - 对我来说是太复杂的话题,我感觉多于理解。因此,如果您指出正确的方法,我会很高兴。

关于reactjs - React HOC 作为类组件有 Typescript 错误,但作为函数组件没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65980069/

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