ReactJS:渲染动态组件并传递道具

时间:2018-10-02 10:03:41

标签: javascript reactjs typescript

在DataGridCell组件中,我需要提供指出哪个组件应呈现单元格内容的功能。道具也需要传递到该组件中。 我试图以另一种方式(简化版)进行操作:

var1.getClass()

我遇到下一个错误: TS2604:JSX元素类型“ Cmp”没有任何构造或调用签名

哪里出了问题?呈现动态组件的正确方法是什么?

UPD 我使用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> ) } } 这样的组件:

DataGridCell

这是一个循环。 <DataGridCell key={indexCell} data={profile} component={cell.component} /> 在配置中,如下所示:cell.componentcomponent: Text是我们的组成部分。

UPD 2 因此,看起来好像不是实现中的问题,而是Textts-lint中的问题。我将组件转换为typescript类型,现在可以正常工作了。 更改的行:any

感谢您提出任何更有价值的解释。

1 个答案:

答案 0 :(得分:2)

应该这样做:

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>
    );
  }
}
相关问题