0

也许有更好的方法,但我尝试让我的 React 组件尽可能地可重用。所以我正在使用引导卡,在这张卡内我想动态地从外部(带有道具)放置不同的组件。没有道具它工作正常。但是使用道具我收到一条错误消息“错误:找不到模块'../../pages/Dummy'”。

这很完美:

import React, {Suspense} from 'react';
import { MDBCard, MDBCardBody } from "mdbreact";

const Area = (props) => {

    const OtherComponent = React.lazy(() => import('../../pages/Dummy'));

    return (
            <MDBCard className="text-center">
                <MDBCardBody>
                    <Suspense fallback={<div>Loading...</div>}>
                        <OtherComponent/>
                    </Suspense>
                </MDBCardBody>
            </MDBCard>
    );
};

export default Area;

这不起作用:

import React, {Suspense} from 'react';
import { MDBCard, MDBCardBody } from "mdbreact";

const Area = (props) => {

    const OtherComponent = React.lazy(() => import(props.compName));

    return (
            <MDBCard className="text-center">
                <MDBCardBody>
                    <Suspense fallback={<div>Loading...</div>}>
                        <OtherComponent/>
                    </Suspense>
                </MDBCardBody>
            </MDBCard>
    );
};

export default Area;

外呼:

<Area compName='../../pages/Dummy'/>

就像我不能用道具延迟加载一样。很奇怪。

顺便提一句。如果有更简单的方法来动态使用子组件,我不需要使用延迟加载。我只是认为这是唯一的方法。

4

1 回答 1

0

有几个选项:

第一个使用“插槽”,您可以在此处阅读 React 文档或此处的文章。

const DummyOne = React.lazy(() => import('../../pages/DummyOne');
const DummyTwo = React.lazy(() => import('../../pages/DummyTwo');

const Area = ({ comp }) => {
  return (
    <MDBCard className="text-center">
      <MDBCardBody>
        <Suspense fallback={<div>Loading...</div>}>
          {comp}
        </Suspense>
      </MDBCardBody>
    </MDBCard>
  );
}

// You dynamically pass the component itself into 'Area'
<Area comp={<DummyOne />} />

第二个选项更接近你所拥有的:

const Area = ({ compName }) => {
  const components = {
    DummyOne: React.lazy(() => import('../../pages/DummyOne'),
    DummyTwo: React.lazy(() => import('../../pages/DummyTwo'),
  }

  const DynamicComponent = components[compName];

  return (
    <MDBCard className="text-center">
      <MDBCardBody>
        <Suspense fallback={<div>Loading...</div>}>
          <DynamicComponent />
        </Suspense>
      </MDBCardBody>
    </MDBCard>
  );
}

// You dynamically pass the component name to 'Area' as a string
<Area compName="DummyOne" />
于 2019-11-24T20:23:17.640 回答