Typescript with React - use HOC on a generic component class

后端 未结 5 2021
别那么骄傲
别那么骄傲 2020-12-30 05:14

I have a generic React component, say like this one:

class Foo extends React.Component, FooState> {
    constructor(props: F         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 05:21

    Just stumbled upon this as well and thought I'd share what I came up with in the end.

    Building on what @rico-kahler provided, my approach mapped to your code would be

    export const FooWithTd = withTd(Foo) as (props: FooProps) => React.ReactElement>;
    

    which you can then use like this

    export class Bar extends React.Component<{}> {
      public render() {
        return (
           />
        );
      }
    }
    

    In my case, I have defaultProps as well and I inject props by ways of another HOC, the more complete solution would look like this:

    type DefaultProps = "a" | "b";
    type InjectedProps = "classes" | "theme";
    type WithTdProps = Omit, DefaultProps | InjectedProps> & Partial & { children: React.ReactNode }>;
    export const FooWithTd = withTd(Foo) as (props: WithTdProps) => React.ReactElement>;
    

提交回复
热议问题