最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to Define ReactNode as a prop for a typescript react component? - Stack Overflow

programmeradmin4浏览0评论

How can I write a React ponent that takes a React ponent as a prop in typescript?

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.

How can I write a React ponent that takes a React ponent as a prop in typescript?

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.

Share Improve this question asked Oct 31, 2020 at 18:45 JeggyJeggy 1,6602 gold badges22 silver badges42 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

You are confusing props type with variable type. 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.

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:

const MyComponent2 = ({ Comp = MyComponent }: {
   Comp: React.ReactNode;
}) => (
interface Props {
    p: 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 ponent. It is the type of the function itself.

发布评论

评论列表(0)

  1. 暂无评论