简体   繁体   English

TypeScript / JSX中的Generic React组件?

[英]Generic React components in TypeScript/JSX?

I would like to create pluggable React components. 我想创建可插入的React组件。 Components are resolved by their class names, so I am naturally drawn to generics; 组件通过其类名解析,因此我很自然地被泛型所吸引; but this doesn't seem to work. 但这似乎不起作用。

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

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

Is there an alternative way to write pluggable TypeScript components? 是否有另一种编写可插入TypeScript组件的方法?

The accepted answer for this question still stands, due to TypeScript types being erased, however as of Typescript 2.9, generic JSX components are supported 由于TypeScript类型被删除,这个问题的接受答案仍然存在,但是从Typescript 2.9开始, 支持通用的JSX组件

The example provided is: 提供的示例是:

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

Just thought it worth mentioning for anyone who ends up here via the question title. 只是觉得值得一提的是那些通过问题标题来到这里的人。

This isn't possible to do using generics, though it's not clear why you would want to use generics for this problem rather than just providing the inner element using the normal props mechanism. 这是不可能使用泛型,虽然不清楚为什么你想要使用泛型来解决这个问题,而不是仅仅使用普通的props机制来提供内部元素。

The reason is that types are erased, so you need to provide the class constructor to the class so that it has a reference to the value to instantiate in C . 原因是类型被擦除,因此您需要向类提供类构造函数,以便它具有对要在C实例化的值的引用。 But there's no place other than the JSX props (or state or whatever you need to do) for you to pass in that value. 但除了JSX props (或state或任何你需要做的事情)之外,没有其他地方可以传递该值。

In other words, instead of writing 换句话说,而不是写作

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

You should write 你应该写

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

and consume it in your render as 并在你的render使用它

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

As an aside, the correct constraint is new() => React.Component rather than React.Component -- remember that the things you write in the JSX ( <Div> , etc) are the constructors for classes, not the class instances . new() => React.Component说一下,正确的约束是new() => React.Component而不是React.Component - 记住你在JSX( <Div>等)中编写的东西是类的构造函数 ,而不是类实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM