TypeScript/JSX中的通用React组件? [英] Generic React components in TypeScript/JSX?

查看:82
本文介绍了TypeScript/JSX中的通用React组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>
        );
    }
}

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

Is there an alternative way to write pluggable TypeScript components?

推荐答案

使用泛型是不可能的,尽管目前尚不清楚为什么要使用泛型来解决此问题,而不仅仅是使用正常的props机制.

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.

原因是类型被删除,因此您需要为该类提供类构造函数,以便它引用要在C中实例化的值.但是除了JSX props(或state或您需要执行的任何操作)之外,没有其他地方可以传递该值.

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.

换句话说,不是写作

// 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() => React.Component而不是React.Component-请记住,您在JSX中编写的内容(<Div>等)是类的构造函数,不是类 instances .

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.

这篇关于TypeScript/JSX中的通用React组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆