React.ReactType:JSX元素类型“ Loader”没有任何构造或调用签名

时间:2019-01-29 10:43:25

标签: reactjs typescript

我想知道如何将JSX(例如“ div”或“ span”)或React组件传递给我自己的组件。因此,我尝试使用React.ReactType来支持两者。我的代码如下所示:

LazySvgIcon.tsx

import * as React from 'react'

interface Props {
  src: string
  loading?: React.ReactType
  error?: React.ReactType
}

interface State {
  isLoading: boolean,
  hasError: boolean
}

export const LazySvgIcon = 
  class LazySvgIcon extends React.Component<Props, State> {
    constructor(props: Props, context?: any) {
      super(props, context)

      this.state = {
        isLoading: false,
        hasError: false
      }
    }

    render() {
      const { isLoading, hasError } = this.state
      const { loading:Loader, error:Error } = this.props
      return(
        <React.Fragment>
          { isLoading && Loader && <Loader /> }
          { hasError && Error && <Error /> }
        </React.Fragment>
      )
    }
  }

但是我的LoaderError组件出现了以下错误...

  

[ts] JSX元素类型'Loader'没有任何构造或调用签名。 [2604]

当我将ReactType更改为ComponentType时,代码正在工作,但这不是我想要的,因为那样我就无法传递<div>容器。

React.ReactType文件中使用*.tsx和TypeScript的正确方法是什么?

使用的版本:TypeScript 3.2.4,React 16.7.0

1 个答案:

答案 0 :(得分:0)

React.ReactType描述了类和功能组件的类型。对于元素,您可以改用React.ReactNode。对于您的示例,尚不清楚是要传递组件(也称为渲染道具)还是将元素作为道具。

如果您要传递元素,请将属性更改为:

interface Props {
    src: string
    loading?: React.ReactNode
    error?: React.ReactNode
}

并在渲染中分解道具时删除类型注释:

const { loading, error: } = this.props

如果要将组件作为道具传递,则要在分解后使用它,则应将其大写,因为JSX会将小写的组件解释为html元素。     界面道具{       src:字符串       LoadingComponent ?: React.ReactType       ErrorComponent ?: React.ReactType     } 并在您的渲染器中:

return(
    <React.Fragment>
      { isLoading && <LoadingComponent /> && <Loader /> }
      { hasError && <ErrorComponent/> && <Error /> }
    </React.Fragment>
  )