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
1 Answer
Reset to default 1This 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
版权声明:本文标题:reactjs - How to extend Parent component by Child subcomponent in Parent object field? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741972686a2407934.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论