[英]TypeScript: How to define the type when pass component in props in React?
Here's the code sample and the JS version is working correctly.这是代码示例,JS 版本工作正常。
The issue I encountered happening in TS :我在 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>
)
}
}
I got an error on <Child Cpnt
我在
<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]
What type should I defind here?我应该在这里定义什么类型?
A React "renderable" is not React.ComponentClass
but React.ReactNode
. React“可渲染”不是
React.ComponentClass
而是React.ReactNode
。
Ask for React.ReactNode
in your Cpnt
prop.问
React.ReactNode
在Cpnt
道具。
您正在传递<Header title='header' />
这是一个 React 元素,而不是Header
,它是一个组件类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.