TypeScript/JSX 中的通用 React 组件?

Generic React components in TypeScript/JSX?

我想创建可插入的 React 组件。组件由它们的 class 名称解析,所以我很自然地被泛型所吸引;但这似乎不起作用。

class Div<P, S, C extends React.Component> extends React.Component<void, void> {

    render() {
        return (
            <div>
                <C /> // error: Cannot find name 'C'.
            </div>
        );
    }
}

是否有其他方法来编写可插入的 TypeScript 组件?

使用泛型不可能做到这一点,但不清楚为什么要使用泛型来解决这个问题,而不是仅仅使用正常的 props 机制提供内部元素。

原因是类型被擦除,所以你需要向class提供class构造函数,以便它具有对要在C中实例化的值的引用。但是除了 JSX props(或 state 或您需要做的任何事情)之外,您没有其他地方可以传递该值。

换句话说,而不是写作

// not sure what you would expect the syntax to be?
const elem = <Div<Foo> ... />; 

你应该写

const elem = <Div myChild={Foo} />

并在你的 render 中消费它作为

const Child = this.props.myChild;
return <div><Child /></div>;

顺便说一句,正确的约束是 new() => React.Component 而不是 React.Component——记住你在 JSX 中写的东西(<Div>,等等)是 constructors for classes, not the class instances.

由于 TypeScript 类型被删除,这个问题的公认答案仍然有效,但是从 Typescript 2.9 开始,generic JSX components are supported

提供的例子是:

class GenericComponent<P> extends React.Component<P> {
    internalProp: P;
}
type Props = { a: number; b: string; };

const x = <GenericComponent<Props> a={10} b="hi"/>; // OK
const y = <GenericComponent<Props> a={10} b={20} />; // Error

只是认为对于通过问题标题来到这里的任何人来说都值得一提。