【问题标题】:Generic React components in TypeScript/JSX?TypeScript/JSX 中的通用 React 组件?
【发布时间】:2016-11-19 06:34:53
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: generics reactjs typescript jsx


    【解决方案1】:

    使用泛型无法做到这一点,但不清楚为什么要使用泛型来解决这个问题,而不是仅仅使用普通的props 机制提供内部元素。

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

    换句话说,不是写

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

    你应该写

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

    并在您的render 中使用它

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

    顺便说一句,正确的约束是 new() =&gt; React.Component 而不是 React.Component -- 请记住,您在 JSX 中编写的内容(&lt;Div&gt; 等)是类的构造函数,不是类实例

    【讨论】:

    • 您能否详细说明擦除类型的含义?您是在谈论将 typescript 代码编译为 javascript 时类型如何消失? (例如,this answer?)
    【解决方案2】:

    由于 TypeScript 类型被删除,这个问题的公认答案仍然有效,但是从 Typescript 2.9 开始,generic JSX components are supported

    提供的例子是:

    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
    

    只是认为对于通过问题标题结束的人来说值得一提。

    【讨论】:

    • 多么奇怪的例子(我当然关注了链接并看到它是官方的)。我真的希望人们不要开始写这样的东西,以为必须这样做。
    猜你喜欢
    • 2022-06-22
    • 2022-12-21
    • 2021-06-17
    • 2019-01-23
    • 2017-05-24
    • 1970-01-01
    • 2017-02-24
    • 2022-12-11
    • 2019-06-06
    相关资源
    最近更新 更多