簡體   English   中英

TypeScript / JSX中的Generic React組件?

[英]Generic React components in TypeScript/JSX?

我想創建可插入的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組件的方法?

由於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

只是覺得值得一提的是那些通過問題標題來到這里的人。

這是不可能使用泛型,雖然不清楚為什么你想要使用泛型來解決這個問題,而不是僅僅使用普通的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() => React.Component說一下,正確的約束是new() => React.Component而不是React.Component - 記住你在JSX( <Div>等)中編寫的東西是類的構造函數 ,而不是類實例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM