打字稿和反应:类型 'Element' 不能分配给类型 'FunctionComponent<{}>'



我正在将一个react项目转换为typescript,我遇到了一个问题。场景是这样的:我有一系列Chapter组件。每个CCD_ 2与其自己的唯一数据和唯一的CCD_ 3分量相关联。每个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组件组织数据、管理状态,并使用React.cloneElement:将某些数据作为道具传递给Map

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>
);
};

我读过这样一个问题:当给孩子们赋予属性时,如何将正确的类型分配给React.cloneElement?,这就是我想到使用ReactElement作为我的map道具的类型的地方。我尝试在cloneElement调用中使用map as ReactElement<any>,但它仍然会给我带来错误,所以我放弃了,暂时使用as null。但我还是犯了这个错误。需要说明的是,代码确实有效,编译-react对我的语法和组织很满意。但是打字脚本是想告诉我一些关于我使用组件作为道具的方式吗?有更合适的方法吗?感谢阅读。

检查这里的代码,这是类型ReactElementFunctionalComponent不匹配的问题

更新:

嘿,你能把它换成吗

const ChapterTemplate = ({
data,
map,
}: { data: any, map: FunctionComponent<MapProps>}) => { // change this to ReactElement
return (<div>Hello world</div>);
}
const Chapter: FunctionComponent<ChapterProps> = (props) => {
return <ChapterTemplate data={props.data} map={Map} />;
};

然后做CCD_ 20

或者做这个

const ChapterTemplate = ({
data,
map,
}: { data: any, map: ReactElement}) => { // change this to ReactElement
return (<div>Hello world</div>);
}
const Chapter: FunctionComponent<ChapterProps> = (props) => {
return <ChapterTemplate data={props.data} map={<Map />} />;
};

最新更新