TypeScript:在 React 中的 props 中传递组件时如何定义类型?

SPG*_*SPG 4 typescript reactjs

这是代码示例,JS 版本工作正常。

我在 TS 中遇到的问题:

import React from 'react'

class Parent extends React.Component {
    render() {
      return (
        <Child Cpnt={<Header title='Header' />} />
        /* TS error on Cpnt */
      )
    }
  }

interface ChildProps {
    Cpnt: React.ComponentClass
}

class Child extends React.Component <ChildProps> {
    render () {
        const { Cpnt } = this.props
        return (
            <div>
                {{Cpnt}}
            </div>
        )
    }
}

interface HeaderProps {
    title: string
}

class Header extends React.Component <HeaderProps> {
    render () {
        const { title } = this.props
        return (
            <p>{title}</p>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个错误 <Child Cpnt

[ts]
Type 'Element' is not assignable to type 'ComponentClass<{}, any>'.
  Type 'Element' provides no match for the signature 'new (props: {}, context?: any): Component<{}, any, any>'. [2322]
Run Code Online (Sandbox Code Playgroud)

我应该在这里定义什么类型?

Mad*_*iha 6

React“可渲染”不是React.ComponentClass但是React.ReactNode

React.ReactNode在你的Cpnt道具中索取。