Типизация вложенных компонентов
import { FC, ReactNode } from 'react'
export const ComponentsPopupExampleTypeProblem = () => {
return (
<ExternalComponent>
<ExternalComponent.InternalComponent>
{/* ^^^^^^^^^^^^^^^^^ Свойство "InternalComponent" не существует в типе "FC<externalComponentProps>*/}
internalComponent content
</ExternalComponent.InternalComponent>
</ExternalComponent>
)
}
type externalComponentProps = { children: ReactNode }
const ExternalComponent: FC<externalComponentProps> = ({ children }) => {
return children
}
type internalComponentProps = { children: ReactNode }
const InternalComponent: FC<internalComponentProps> = ({ children }) => {
return children
}
ExternalComponent.InternalComponent = InternalComponent
// ^^^^^^^^^^^^^^^^^
// Свойство "InternalComponent" не существует в типе "FC<{ children: ReactNode; }>"
import { FC, ReactNode } from 'react'
export const ComponentsPopupExampleTypeProblem = () => {
return (
<ExternalComponent>
<ExternalComponent.InternalComponent>
internalComponent content
</ExternalComponent.InternalComponent>
</ExternalComponent>
)
}
// type ExternalComponentProps = { children: ReactNode }
// const ExternalComponent = ({children}: ExternalComponentProps) => {
// return children
// }
// type InternalComponentProps = { children: ReactNode }
// const InternalComponent = ({children}: InternalComponentProps) => {
// return children
// }
// ExternalComponent.InternalComponent = InternalComponent
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Ошибок нет но, если вынести InternalComponent в другой файл или типизировать как FC<...>
type externalComponentProps = { children: ReactNode }
const ExternalComponent: FC<externalComponentProps> = ({ children }) => {
return children
}
type internalComponentProps = { children: ReactNode }
const InternalComponent: FC<internalComponentProps> = ({ children }) => {
return children
}
ExternalComponent.InternalComponent = InternalComponent
// ^^^^^^^^^^^^^^^^^
// Свойство "InternalComponent" не существует в типе "FC<{ children: ReactNode; }>"
/* с GPT аналогичная проблема
Вот пример реализации вложенных компонентов в React с использованием TypeScript:
type AppProps = {
children: React.ReactNode;
};
const App: React.FC<AppProps> = ({ children }) => {
return <div className="app">{children}</div>;
};
type ContentProps = {
title: string;
};
const Content: React.FC<ContentProps> = ({ title }) => {
return <h1>{title}</h1>;
};
const ExampleComponent: React.FC = () => {
return (
<App>
<App.Content title="Nested Component Example" />
^^^^^^^^ Свойство "Content" не существует в типе "FC<AppProps>"
</App>
);
};
export default ExampleComponent;
В этом примере App - это внешний компонент, а Content - вложенный компонент, который может быть использован только внутри App. Обратите внимание, что вложенный компонент Content передается в App как его дочерний элемент с использованием синтаксиса <App.Content />. */
Источник: Stack Overflow на русском