创建一个返回反应组件类的打字稿功能

时间:2020-02-19 15:13:09

标签: reactjs typescript

我需要创建一个实用程序函数,该函数将根据某些条件返回反应组件类之一(而不是实例)。因此,函数的返回类型应该是通用的(React.PureComponent)

import React from 'react';
class FooOne extends React.PureComponent {
    render(): React.ReactElement {
        return null;
    }
}
class FooTwo extends React.PureComponent {
    render(): React.ReactElement {
        return null;
    }
}
function getFooClass(condition: boolean): typeof React.PureComponent {
    return condition ? FooOne : FooTwo;
}
const SomeFooClass = getFooClass(true);
const instance: React.PureComponent = new SomeFooClass();
上面的

代码通常可以工作(我仍然不明白为什么我需要使用 typeof React.PureComponent 作为getFooClass的返回类型,这是通过实验发现的), 但是打字稿会为getFooClass产生以下错误:

Type 'typeof FooOne' is not assignable to type 'typeof PureComponent'.
  Construct signature return types 'FooOne' and 'PureComponent<P, S>' are incompatible.
    The types of 'props' are incompatible between these types.
      Type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>' is not assignable to type 'Readonly<{ children?: ReactNode; }> & Readonly<P>'.
        Type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>' is not assignable to type 'Readonly<P>'.

也许这是打字稿错误或限制?

2 个答案:

答案 0 :(得分:1)

尝试类似

function getFooClass(condition: boolean): React.ComponentType {
   // if FooOne and FooTwo have arguments you can use React.ComponentType<TArgs>
   return condition ? FooOne : FooTwo;
}

用法应该是这样

function render() {
    const FooEl = getFooClass(true); // PascalCase is required
    return <FooEl />
}

或仅返回创建的实例

function getFooClass(condition: boolean): JSX.Element  {
   return condition ? <FooOne /> : <FooTwo />;
}

答案 1 :(得分:0)

React.ReactNode在这种情况下应该可以工作:

function getFooClass(condition: boolean): React.ReactNode {
  return condition ? FooOne : FooTwo;
}