Generic React components in TypeScript/JSX?

你说的曾经没有我的故事 提交于 2019-12-21 07:54:42

问题


I would like to create pluggable React components. 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?


回答1:


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.

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. 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.

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

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.




回答2:


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

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.



来源:https://stackoverflow.com/questions/38406448/generic-react-components-in-typescript-jsx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!