TypeScript/JSX中的Generic React组件?

Car*_*lin 9 generics jsx typescript reactjs

我想创建可插入的React组件.组件通过其类名解析,因此我很自然地被泛型所吸引; 但这似乎不起作用.

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

    render() {
        return (
            <div>
                <C /> // error: Cannot find name 'C'.
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有另一种编写可插入TypeScript组件的方法?

Jon*_*Job 13

由于TypeScript类型被删除,这个问题的接受答案仍然存在,但是从Typescript 2.9开始,支持通用的JSX组件

提供的示例是:

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
Run Code Online (Sandbox Code Playgroud)

只是觉得值得一提的是那些通过问题标题来到这里的人.


Rya*_*ugh 10

这是不可能使用泛型,虽然不清楚为什么你想要使用泛型来解决这个问题,而不是仅仅使用普通props机制提供内部元素.

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

换句话说,而不是写作

// not sure what you would expect the syntax to be?
const elem = <Div<Foo> ... />; 
Run Code Online (Sandbox Code Playgroud)

你应该写

const elem = <Div myChild={Foo} />
Run Code Online (Sandbox Code Playgroud)

并在你的renderas中消费它

const Child = this.props.myChild;
return <div><Child /></div>;
Run Code Online (Sandbox Code Playgroud)

顺便说一下,正确的约束new() => React.Component不是React.Component- 记住你在JSX(<Div>等)中编写的东西是类的构造函数,而不是类实例.