Generic React components in TypeScript/JSX?

后端 未结 2 821
被撕碎了的回忆
被撕碎了的回忆 2021-02-19 07:23

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.

<         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-19 08:13

    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 =  ... />; 
    

    You should write

    const elem = 

    and consume it in your render as

    const Child = this.props.myChild;
    return 
    ;

    As an aside, the correct constraint is new() => React.Component rather than React.Component -- remember that the things you write in the JSX (

    , etc) are the constructors for classes, not the class instances.

提交回复
热议问题