[英]ReactJS: Render dynamic Component and pass props
在 DataGridCell 組件中,我需要提供指向哪個組件應該呈現單元格內容的能力。 還需要將道具傳遞到此組件中。 我嘗試以下一種方式(簡化版)來做到這一點:
import * as React from 'react';
interface IDataGridCellProps {
data?: any,
component?: React.Component,
}
export default class DataGridCell extends React.Component<IDataGridCellProps> {
public render() {
const Cmp: React.Component<any> = this.props.component as React.Component;
return (
<div>
<Cmp {...this.props.data} />
</div>
)
}
}
我收到下一個錯誤:TS2604:JSX 元素類型“Cmp”沒有任何構造或調用簽名
有什么問題,渲染動態組件的正確方法是什么?
UPD然后我使用DataGridCell
組件,如下所示:
<DataGridCell key={indexCell}
data={profile}
component={cell.component}
/>
這是一個循環。 cell.component
在配置中,看起來像這樣: component: Text
。 Text
是我們的組件。
UPD 2所以它看起來不是在實現中而是在ts-lint
和typescript
。 我將組件轉換為any
類型,現在可以使用了。 更改行: const Cmp: any = this.props.component;
任何更有價值的解釋表示贊賞。
應該這樣做:
interface IDataGridCellProps
{
data?: any;
component?: React.ComponentType<any>;
}
export default class DataGridCell extends React.Component<IDataGridCellProps> {
public render()
{
const Cmp = this.props.component;
if (Cmp)
{
return (
<div>
<Cmp {...this.props.data} />
</div>
);
}
return null;
}
}
TypeScript 現在可以正確處理 jsx 中的泛型,因此它可以是:
interface IDataGridCellProps<T>
{
data?: T;
component?: React.ComponentType<T>;
}
export default class DataGridCell<T> extends React.Component<IDataGridCellProps<T>> {
public render()
{
const Cmp = this.props.component;
if (this.props.data === undefined || Cmp === undefined)
{
return null;
}
return (
<div>
<Cmp {...this.props.data} />
</div>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.