简体   繁体   English

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

[英]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.ReactNodeCpnt道具。

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

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

相关问题 如何将条件道具传递给 typescript 中未知类型的反应组件? - How to pass conditional props to unknown type of react component in typescript? 如何使用 React TypeScript 将组件传递给道具? - How to pass component to props using React TypeScript? 反应 select - 如何定义组件道具类型 - react select - how to define component props type 如何为React props定义TypeScript类型,只有在将prop A传递给组件时,才会接受prop B? - How do I define a TypeScript type for React props where prop B is only accepted if prop A is passed to a component? 如何在 React 组件 props 中传递通用类型 - How to pass a generic type in a React component props 如何使用 typescript 在 React 功能组件中定义自定义道具? - How to define custom props in a react functional component with typescript? 如何使用反应表和 typescript 传递道具以反应功能组件? - How to pass the props to react functional component using react table and typescript? React - 如何使用打字稿定义道具 - React - How to define props with typescript 当我们使用 React 和 Typescript 时,如何有条件地将可选道具传递给组件? - How to conditionally pass optional props to component when we use React with Typescript? 如何将道具传递给 function 并使用 react 和 typescript 在组件中访问它? - How to pass props to a function and access it in a component using react and typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM