我想创建一个 HOC,我可以在其中提供一组 props 并在其中任何一个未定义时进行检查:如果是这样,则会显示带有微调器的 Loading 组件而不是包装的组件。
这是容易的部分。
由于这些props不能未定义(否则会显示微调器),我希望它们是可选props:
const MyComponentWithLoading = withLoading(MyComponent);
return (
<MyComponentWithLoading
loadingFields={['user']}
user={user} // MyComponent requires "user" to not be undefined, but since it's in "loadingFields" it can actually be undefined
device={device} // MyComponent requires "device" to not be undefined and it must be so because it's not in "loadingFields"
/>
);
我尝试使用以下代码,但它不起作用。知道如何实现这一目标吗?
import React, {FC, ComponentType, PropsWithChildren} from 'react';
import Loading from '@components/Loading';
type WithLoadingProps<T> = {
loadingFields?: Array<
keyof Omit<PropsWithChildren<T & WithLoadingProps<T>>, 'loadingFields'>
>;
};
const withLoading =
<T,>(
Component: ComponentType<T>,
): FC<
Partial<Pick<T, keyof WithLoadingProps<T>['loadingFields']>> &
Omit<T, keyof WithLoadingProps<T>['loadingFields']> &
WithLoadingProps<T>
> =>
({loadingFields: loadingData = [], ...otherProps}) => {
const isLoading = (): boolean => {
for (const key of loadingData) {
if (otherProps[key] === undefined) {
return true;
}
}
return false;
};
return isLoading() ? <Loading /> : <Component {...(otherProps as T)} />;
};
export default withLoading;