reactjs - 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]
我应该在这里定义什么类型?
解决方案
React 的“可渲染”不是React.ComponentClass
but React.ReactNode
。
React.ReactNode
在你的Cpnt
道具中询问。
推荐阅读
- html - 如何为列表添加多个过滤器并在角度 7 中单独取消选中它们?
- serial-port - Raspberry Pi 3 Model B(Android things OS)错误:无法打开/dev/ttyAMA0:没有这样的文件或目录
- javascript - 使用 Reactjs 动态添加、删除和编辑输入值
- jmeter - 在表侦听器中查看结果未捕获 BeanShell 失败/成功
- paypal - Paypal 创建支付令牌 API 返回 422 无法处理的实体
- spring - Spring Boot 中的自定义异常处理
- swift - DispatchQueue 冻结主队列
- python - Python从枚举类返回int
- moodle - 在 Moodle 中打开编辑不显示
- python - 一种将 n 最大元素保留在矩阵中的行或列中的稳健方法