0

当尝试preload()为组件实现方法时React.lazy(),典型的模式看起来像,

const ReactLazyPreload = (importStatement) => {
  const Component = React.lazy(importStatement);
  Component.preload = importStatement; // Property 'preload' does not exist on type 'LazyExoticComponent<T>'.
  return Component;
};

以后可以使用,例如,

const MyComponent = ReactLazyPreload(() => import("./MyComponent.tsx");
const onHover = () => { MyComponent.preload() };

但是,第一个片段第 3 行的赋值会导致 TS 错误,

Property 'preload' does not exist on type 'LazyExoticComponent<T>'.

我一直在玩declare,但未能成功消除错误。该方法应该使用什么类型preload()

4

2 回答 2

1
// extend lazy component with `preload` property
interface LazyPreload<Props>
  extends React.LazyExoticComponent<React.ComponentType<Props>> {
  preload: () => {};
}

function ReactLazyPreload<Props>(
  importStatement: () => Promise<{ default: React.ComponentType<Props> }>
) {
  // use Object.assign to set preload
  // otherwise it will complain that Component doesn't have preload
  const Component: LazyPreload<Props> = Object.assign(
    React.lazy(importStatement),
    {
      preload: importStatement,
    }
  );

  return Component;
}
于 2021-12-10T10:23:57.933 回答
1

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

于 2021-12-10T11:53:45.297 回答