首页 > 解决方案 > TypeScript:如何在 React 的 props 中传递组件时定义类型?

问题描述

这是代码示例,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>
        )
    }
}

我有一个错误<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]

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

标签: reactjstypescript

解决方案


React 的“可渲染”不是React.ComponentClassbut React.ReactNode

React.ReactNode在你的Cpnt道具中询问。


推荐阅读