3

我在这样的文件中有一个反应功能组件-

const Slot: React.ElementType = () => null;
const Component = ({ children }): JSX.Element | null => {
  const childrenArr = React.Children.toArray(children) as React.ReactElement[];
  const slot = childrenArr.find(child => child.type === Slot);

  return (
    <div>
      <div>Hi</div>
      {slot && slot.props.children}
    </div>
  );
};

Component.Slot = Slot;
export default Component;

我正在使用这个组件,将它导入另一个使用React.lazy

const Comp = React.lazy(() => import(/* webpackChunkName: "comp" */ './Component'))

我正在渲染这个组件React.Suspense,就像这样

 <Suspense fallback={null}>
   <Comp>
     Welcome
     <Comp.Slot>Robert</Comp.Slot>
   </Comp>
 </Suspense>

Robert不是渲染。另外,我收到 Typescript 错误Comp.Slot,说

Property 'Slot' does not exist on type 'LazyExoticComponent<{ (): Element | null; Slot: FunctionComponent<any>;}>'.

解决此问题的最佳方法是什么?请帮忙。

4

1 回答 1

1

我相信lazy仅适用于默认导出,并且仅适用于导出的确切组件,因为它会围绕它创建某种 HOC。

你能做的就是做这部分

   <Comp>
     Welcome
     <Comp.Slot>Robert</Comp.Slot>
   </Comp>

独立组件并在其上使用惰性。

于 2020-06-26T09:44:30.737 回答