gpt4 book ai didi

reactjs - typescript 高阶组件

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

我在输入以下 HOC 时遇到问题。我已经简化了它,但用例是根据新的 prop 修改包装组件上的类。

import React, { ComponentType } from 'react';

interface Classable {
className?: string;
}

interface Fooable {
foo: string;
}

function fooTheClass(foo: string, className?: string): string {
// this is a simplified example..
return className ? `$(className) ${foo}` : foo;
}

// HOC to modify className based on a new prop.
const withFoo = <P extends Classable>(Component: ComponentType<P>): ComponentType<P & Fooable> => {
const newComponent = ({ foo, className, ...rest }: P & Fooable) => {
return <Component className={fooTheClass(foo, className)} {...rest} />;
};
return newComponent;
};

这会导致以下错误:

Type '{ className: string; } & Pick>' is not assignable to type 'IntrinsicAttributes & P & { children?: ReactNode; }'. Type '{ className: string; } & Pick>' is not assignable to type 'P'. [2322]

如果我不解构,我可以消除错误:

const withFoo1 = <P extends Classable>(Component: ComponentType<P>): ComponentType<P & Fooable> => {
const newComponent = (props: P & Fooable) => {
const { ...rest } = props;
rest.className = fooTheClass(rest.foo, rest.className);
delete rest.foo;
return <Component {...rest } />;
};
return newComponent;
};

或使用显式转换:

const withFoo2 = <P extends Classable>(Component: ComponentType<P>): ComponentType<P & Fooable> => {
const newComponent = ({ foo, className, ...rest }: P & Fooable) => {
return <Component className={fooTheClass(foo, className)} {...(rest as unknown as P)} />;
};
return newComponent;
};

(注意只是:

return <Component className={fooTheClass(foo, className)} {...(rest as P)} />;

不会工作)。

这些似乎都是不优雅的解决方法。有没有更好的办法?

最佳答案

我认为你能做的最好的事情就是使用预定义的 React.FC 类型而不是直接输入 props:

const withFoo = <P extends Classable>(
Component: ComponentType<P>
): ComponentType<P & Fooable> => {
const newComponent: React.FC<P & Fooable> = ({ foo, className, ...rest }) => {
return <Component className={fooTheClass(foo, className)} {...rest as P} />;
};
return newComponent;
};

关于reactjs - typescript 高阶组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54401691/

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