TypeScript 试图防止你在这里犯错。
仅仅因为其他人遵循约定并不能使它成为一个好的约定:在这种情况下,它不是一个安全的约定。作为一般规则,对你不拥有的东西进行变异是不安全的。
虽然我在 React 代码库中的当前版本17.0.2
标记preload
(在随后的版本中的财产。如果发生这种情况,并且您覆盖了该属性,则会出现不可预测的行为。
无需改变组件,只需在其旁边返回 preload 函数:
TS Playground 链接
import {default as React, lazy} from 'react';
import type {ComponentType, LazyExoticComponent} from 'react';
export type ReactLazyFactory<T = any> = () => Promise<{default: ComponentType<T>}>;
export type ComponentPreloadTuple<T = any> = [
component: LazyExoticComponent<ComponentType<T>>,
preloadFn: () => void,
];
export function getLazyComponentWithPreload <T = any>(componentPath: string): ComponentPreloadTuple<T>;
export function getLazyComponentWithPreload <T = any>(factory: ReactLazyFactory<T>): ComponentPreloadTuple<T>;
export function getLazyComponentWithPreload <T = any>(input: string | ReactLazyFactory<T>): ComponentPreloadTuple<T> {
const factory = () => typeof input === 'string' ? import(input) : input();
return [lazy(factory), factory];
}
// ----------
// Example.tsx
export type ExampleProps = {
text: string;
};
export default function ExampleComponent ({text}: ExampleProps) {
return <div>{text}</div>;
}
// ----------
// AnotherComponent.tsx
// use with path to component:
const [Example1, preloadExample1] = getLazyComponentWithPreload<ExampleProps>('./Example');
// use with factory function:
const [Example2, preloadExample2] = getLazyComponentWithPreload<ExampleProps>(() => import('./Example'));