【发布时间】:2020-09-24 17:51:38
【问题描述】:
我正在尝试在我的 HOC 中使用 React Hooks 将一个事件传递给父级,说明该组件何时位于 Viewport 上,以便使用 React Intersection Observer 延迟加载此组件数据,但我正在努力解决以下错误: Type '(props: IStockProps) => JSX.Element | JSX.Element[]' is not assignable to type 'FC<IStockProps>'.
我最近开始使用 Typescript,但我仍在学习如何阅读这些错误,有时可能会有点混乱。这是我的代码
HOC
import React, { useEffect, ComponentType, Component } from "react";
import { useInView } from "react-intersection-observer";
interface IHocProps {
[key: string]: any;
}
export const LazyLoader = (WrappedComponent: ComponentType<IHocProps>) =>
function Comp(props: IHocProps) {
const { onEnterView } = props;
const [ref, inView] = useInView({
triggerOnce: true,
});
useEffect(() => {
inView && onEnterView();
}, [inView]);
return <WrappedComponent ref={ref} {...props} />;
};
组件:
import React from "react";
import { Skeleton, Space } from "antd";
interface IStockProps {
isLoading: boolean;
stockSituation: object;
}
export const StockSituation: React.FC<IStockProps> = (props: IStockProps) => {
const { isLoading, stockSituation } = props;
const renderSkeleton = (
<>
<Skeleton paragraph={{ rows: 2 }} active={true} />
<Space
style={{ justifyContent: "center" }}
direction="horizontal"
align="center"
size="large"
>
<Skeleton.Avatar size={200} active={true} />
<Skeleton.Avatar size={200} active={true} />
<Skeleton.Avatar size={200} active={true} />
<Skeleton.Avatar size={200} active={true} />
</Space>
</>
);
return isLoading
? renderSkeleton
: Object.keys(stockSituation).map((stock) => (
<p>{stockSituation[stock as keyof IStockProps["stockSituation"]]}</p>
));
};
仪表板
import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "@store";
import {getStock, IStock} from "@store/dashboard/dashboard";
import { Grid, Row, Col } from "react-flexbox-grid";
import {LazyLoader} from "@components";
const stock: IStock = useSelector(
({ dashboard: { stock } }: RootState) => stock
);
const loadInfo = () => {
console.log("info");
dispatch(getStock());
};
const LazyStockSituation = LazyLoader(StockSituation);
return (
<>
<Header />
<Grid>
<Row>
<Col>
<LazyStockSituation
onEnterView={loadInfo}
stockSituation={stock}
isLoading={!stock}
/>
</Panel>
</Col>
</Row>
</Grid>
</>
);
};
编辑:所以,我发现这个错误是由组件引起的,而不是由 HOC 引起的,所以我修复了它,但现在我遇到了新的错误,更可怕
Argument of type 'FC<IStockProps>' is not assignable to parameter of type 'ComponentType<IHocProps>'.
Type 'FunctionComponent<IStockProps>' is not assignable to type 'FunctionComponent<IHocProps>'.
Types of parameters 'props' and 'props' are incompatible.
Type 'PropsWithChildren<IHocProps>' is not assignable to type 'PropsWithChildren<IStockProps>'.
Type 'PropsWithChildren<IHocProps>' is missing the following properties from type 'IStockProps': isLoading, stockSituation
所有这些错误都是关于尝试将带有接口IHocProps 的props 传递给接收带有接口IStockProps 的props 的组件,对吧?有没有办法让我的 HOC 接收更通用的可能类型,以便我可以将它与任何其他组件一起使用?
【问题讨论】:
标签: javascript reactjs typescript react-hooks