我正在将react项目转换为Typescript,但是遇到了问题。场景是这样的:我有一系列Chapter
组件。每个Chapter
与它自己的唯一数据和唯一Map
组件相关联。每个Chapter
呈现一个ChapterTemplate
,并通过Map
作为道具:
// Chapter.tsx
import model from './modal';
import Map from './Map';
type ChapterProps = {
data: ModelSchema;
map: ReactElement;
};
const Chapter: FunctionComponent<ChapterProps> = () => {
return <ChapterTemplate data={model} map={<Map />} />;
};
这给了我map={<Map />}
处以下ts错误:
Type 'Element' is not assignable to type 'FunctionComponent<{}>'. Type 'Element' provides no match for the signature '(props: { children?: ReactNode; }, context?: any): ReactElement<any, any>'.
我不确定如何根据我的使用方式输入该道具。
在某些情况下,<Map />
组件应如下所示:
type MapProps = {
metadata?: {
name: string;
theme: string;
};
mapState?: {
center: number[];
zoom: number;
basemap: any;
layers: any[];
};
};
const Map = ({
metadata,
mapState: { basemap, layers, zoom, center },
}: MapProps) => {
// ... custom logic here for each chapter ...
}
最终,ChapterTemplate
组件可以组织数据,管理状态,并使用Map
作为道具将某些数据传递给React.cloneElement
:
const Chapter = ({
map,
data: { pages, metadata },
}: ChapterProps) => {
const [currentPage, setCurrentPage] = useState(0);
const Map = map;
return (
<Wrapper>
// Some other stuff in here
<MapContainer>
{cloneElement(map as null, {
mapState: pages[currentPage].mapState,
metadata,
})}
</MapContainer>
</Wrapper>
);
};
我阅读了问题How to assign the correct typing to React.cloneElement when giving properties to children?,在这里我想到了将ReactElement
用作我的map
道具的类型的想法。我在map as ReactElement<any>
通话中尝试使用cloneElement
,但它仍然给我带来错误,因此我放弃并暂时放下as null
。但是我仍然收到此错误。作为记录,代码确实可以工作和编译-react对我的语法和组织感到满意。但是打字稿是否试图告诉我一些有关我将组件用作道具的方式的信息?有没有更合适的方法可以做到这一点?感谢您的阅读。