繁体   English   中英

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

[英]TypeScript: How to define the type when pass component in props in React?

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

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

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

React.ReactNodeCpnt道具。

您正在传递<Header title='header' />这是一个 React 元素,而不是Header ,它是一个组件类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM