Generics TypeScript/JSX中的通用React组件?

Generics TypeScript/JSX中的通用React组件?,generics,reactjs,typescript,jsx,Generics,Reactjs,Typescript,Jsx,我想创建可插拔的组件。组件是通过它们的类名来解析的,所以我自然会被泛型所吸引;但这似乎不起作用 class Div<P, S, C extends React.Component> extends React.Component<void, void> { render() { return ( <div> <C /> // error: Cannot find na

我想创建可插拔的组件。组件是通过它们的类名来解析的,所以我自然会被泛型所吸引;但这似乎不起作用

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

    render() {
        return (
            <div>
                <C /> // error: Cannot find name 'C'.
            </div>
        );
    }
}
class Div扩展了React.Component{
render(){
返回(
//错误:找不到名称“C”。
);
}
}

有没有其他方法可以编写可插入的TypeScript组件?

使用泛型是不可能的,尽管不清楚为什么要使用泛型来解决这个问题,而不仅仅是使用普通的
道具
机制来提供内部元素

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

换句话说,不是写作

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

另一方面,正确的约束是
new()=>React.Component
,而不是
React.Component
——请记住,您在JSX中编写的东西(
等)是类的构造函数,而不是类实例。

这个问题的公认答案仍然有效,因为类型脚本类型被删除,但是,从Typescript 2.9开始

提供的示例是:

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
class GenericComponent

扩展了React.Component

{ 内标:P; } 类型Props={a:number;b:string;}; 常数x=;//好啊 常数y=;//错误


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

你能详细说明删除一个类型意味着什么吗?你是说当typescript代码被编译成javascript时,类型是如何消失的?(例如?)这是一个多么奇怪的例子(我当然遵循了链接,看到它是一个官方的链接)。我真的希望人们不要开始写这样的东西,以为这就是必须做的。
const Child = this.props.myChild;
return <div><Child /></div>;
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