我有一個延遲加載組件,其中有 3 個引數:
- children:是傳遞給
Suspense組件的組件。 - 高度:是
height用于LazyLoad組分負載圖示。 - 寬度:是
width用于LazyLoad組分負載圖示。
該LazyLoad組件如下:
import React from "react";
import { Suspense } from "react";
import Loading from "../Loading/Loading";
interface LazyLoadCompProps {
children : React.ReactNode;
height ?: string;
width ?: string;
}
const defaultProps: LazyLoadCompProps = {
children,
height: "300px",
width: "300px"
}
const LazyLoad = (props: LazyLoadCompProps) => {
const {children, height, width} = props;
return (
<Suspense fallback={<Loading height={height} width={width} />}>
{children}
</Suspense>
);
};
LazyLoad.defaultProps = defaultProps;
export default LazyLoad;
但是當我啟動應用程式時npm start拋出以下錯誤:
TypeScript error in [project]/src/features/GenericComponents/LazyLoad/LazyLoad.tsx(5,21):
Binding element 'children' implicitly has an 'any' type. TS7031
3 | import Loading from "../Loading/Loading";
4 |
> 5 | const LazyLoad = ({ children, height = "300px", width = "300px" }) => {
| ^
6 | return (
7 | <Suspense fallback={<Loading height={height} width={width} />}>
8 | {children}
但是我希望引數children是必需的但沒有可選值,我該怎么做?
uj5u.com熱心網友回復:
最好的方法是使用React.FC型別。這將注入children變數。您還可以在函式引數中設定默認變數。
import React from "react";
import { Suspense } from "react";
import Loading from "../Loading/Loading";
interface LazyLoadCompProps {
height?: string;
width?: string;
}
const LazyLoad: React.FC<LazyLoadCompProps> = ({children, height = "300px", width = "300px"}) => {
return (
<Suspense fallback={<Loading height={height} width={width} />}>
{children}
</Suspense>
);
};
export default LazyLoad;
uj5u.com熱心網友回復:
為了解決這個問題,我在 2 個不同的介面中添加了必需和可選引數,然后將可選和必需的引數擴展到另一個介面,如下所示:
import React from "react";
import { Suspense } from "react";
import Loading from "../Loading/Loading";
interface LazyLoadRequiredProps {
children : React.ReactNode;
}
interface LazyLoadOptionalProps {
height ?: string;
width ?: string;
}
interface LazyLoadProps extends LazyLoadRequiredProps, LazyLoadOptionalProps {}
const defaultProps: LazyLoadOptionalProps = {
height: "300px",
width: "300px",
}
const LazyLoad = (props: LazyLoadProps) => {
const {children, height, width} = props;
return (
<Suspense fallback={<Loading height={height} width={width} />}>
{children}
</Suspense>
);
};
LazyLoad.defaultProps = defaultProps;
export default LazyLoad;
我從以下來源看到這個例子:https : //dev.to/fullstackchris/react-with-typescript-optional-props-with-default-values-33nc
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/366071.html
標籤:javascript 反应 打字稿
上一篇:基于函式數量的型別保護
