admin管理员组

文章数量:1315025

I'm trying to add custom field to Parent component(because it is a JS object) with creating subcomponent (to get some hierarchical export).

But got typescript error: JSX element type 'Item' does not have any construct or call signatures.

What problem is? Need some help to understand it.

// Component.js

interface Props {
    children: React.ReactNode
}

const Parent: React.FC<Props> & { Item?: React.FC } = ({ children }) => {
    return <div>{children}</div>;
}

const Child: React.FC<Props> = () => {
    return <span>Child</span>;
}

Parent.Item = Child;

export default Parent;



// App.js

import { default as Parent } from 'component.js';

const { Item } = Parent;

const App = () => {
    return (
        <Parent>
            <Item/> {/* Typescript error here */}
            <Item/> {/* Typescript error here */}
            <Item/> {/* Typescript error here */}
        </Parent>
    );
}

I'm trying to add custom field to Parent component(because it is a JS object) with creating subcomponent (to get some hierarchical export).

But got typescript error: JSX element type 'Item' does not have any construct or call signatures.

What problem is? Need some help to understand it.

// Component.js

interface Props {
    children: React.ReactNode
}

const Parent: React.FC<Props> & { Item?: React.FC } = ({ children }) => {
    return <div>{children}</div>;
}

const Child: React.FC<Props> = () => {
    return <span>Child</span>;
}

Parent.Item = Child;

export default Parent;



// App.js

import { default as Parent } from 'component.js';

const { Item } = Parent;

const App = () => {
    return (
        <Parent>
            <Item/> {/* Typescript error here */}
            <Item/> {/* Typescript error here */}
            <Item/> {/* Typescript error here */}
        </Parent>
    );
}
Share Improve this question edited Jan 30 at 10:36 jonrsharpe 122k30 gold badges267 silver badges474 bronze badges asked Jan 30 at 10:33 JonSnowKnowsNothingJonSnowKnowsNothing 174 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

This error occurs because TypeScript treats Item as optional, causing it to be undefined. The fix is to type Parent as React.FC<Props> & { Item: React.FC }, ensuring Item is always present. This eliminates the type error and allows Item to be used as a valid React component.

// Component.tsx
import React from 'react';

interface Props {
  children?: React.ReactNode;
}

const Parent: React.FC<Props> & { Item: React.FC } = ({ children }) => {
  return <div>{children}</div>;
};

const Child: React.FC = () => <span>Child</span>;

Parent.Item = Child;

export default Parent;

// App.tsx
import Parent from './Component';

const App = () => (
  <Parent>
    <Parent.Item />
    <Parent.Item />
    <Parent.Item />
  </Parent>
);

export default App;

本文标签: reactjsHow to extend Parent component by Child subcomponent in Parent object fieldStack Overflow