简体   繁体   English

如何将 ReactNode 定义为打字稿反应组件的道具?

[英]How to Define ReactNode as a prop for a typescript react component?

How can I write a React component that takes a React component as a prop in typescript?如何编写一个将 React 组件作为打字稿中的道具的 React 组件?

I want to write code something like this:我想写这样的代码:

const MyComponent = () => (
  <span>Hello</span>
);

// this throws "TS2339: Property 'Comp' does not exist on type 'FC{ Comp: FC ; }>'."
const MyComponent2 = ({ Comp = MyComponent }: React.FC<{
  Comp: React.ReactNode;
}>) => (
  <span>
    <Comp />
  </span>
);

I do not want to use something like any or disabling the typescript type checking.我不想使用类似any或禁用打字稿类型检查的东西。

You are confusing props type with variable type.您将 props 类型与变量类型混淆了。 What you have actually done here:你在这里实际做了什么:

= ({ Comp = MyComponent }: React.FC<{
  Comp: React.ReactNode;
}>)

basically you told TS that the props object is a React.FC , which obviously isn't.基本上你告诉 TS props 对象是一个React.FC ,这显然不是。

So either move the type just right after variable declaration:因此,要么在变量声明后立即移动类型:

const MyComponent2: React.FC<{
   Comp: React.ReactNode;
}> = ({ Comp = MyComponent }) => (

or just remove the React.FC :或者只是删除React.FC

const MyComponent2 = ({ Comp = MyComponent }: {
   Comp: React.ReactNode;
}) => (
interface Props {
    comp: JSX.Element // (or React.ReactNode or React.FC, whatever your use case is)
}

const MyComponent: React.FC<Props> = (props) => {}

I don't believe React.FC is the return type of a component.我不相信 React.FC 是组件的返回类型。 It is the type of the function itself.它是函数本身的类型。

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

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