使用带有道具的子组件进行动态反应

时间:2019-11-24 18:00:53

标签: javascript reactjs mdbootstrap

也许有更好的方法,但是我尝试使我的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'/>

这就像我无法延迟加载道具。很奇怪。

顺便说一句。如果有一种更简便的方式动态使用子组件,则无需使用延迟加载。我只是认为这是唯一的方法。

1 个答案:

答案 0 :(得分:0)

有几种选择:

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

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" />