React:动态导入jsx

时间:2016-04-17 14:23:01

标签: reactjs

此问题与将JSX文件动态导入React有关。

基本上我们有一个主要组件,它根据存储在数据库中的结构动态呈现其他组件。动态组件存储在子目录" ./ Components"中。我们将其静态定义为:

import CompA  from './Components/CompA';
import CompB  from './Components/CompB';

var components = {
 'CompA': CompA,
 'CompB': CompB
}

我们使用以下方式渲染它们:

var type = 'CompA' 
var Component = components[type];
...
<Component />

虽然这很好用但对我们来说有点太静态了。我们有100多个组件(CompA / CompBs)并静态定义它们不起作用。

是否可以在&#34; ./ Compontents&#34;中导入所有JSX文件?并填充components-array?

而且,如果我们能够发送&#34; ./ Components&#34;路径作为主要组件的支柱。主要组件将使用此路径导入.jsx文件。像这样:

<MainComponent ComponentPath="./SystemComponents">

将使用&#34; ./ SystemComponents&#34;作为.JSX文件的路径,并且:

<MainComponent ComponentPath="./UserComponents">

会使用&#34; ./ UserComponents&#34;作为导入路径。

3 个答案:

答案 0 :(得分:8)

如果组件/ index.js包含内容:

export CompA from "./comp_a";
export CompB from "./comp_b";

然后你做:

import * as Components from "./components"

然后你会用作:

<Components.CompA />
<Components.CompB />
...

希望这有帮助。

我怀疑你在通过组件道具发送路径时可以加载任何东西,然后在React组件生命周期方法中加载文件,这不是我推荐的。

答案 1 :(得分:0)

为了补充@ gor181的答案,我可以补充说export必须是这样的:

export { default as CompA } from "./comp_a"; export { default as CompB } from "./comp_b";

希望这可能会有所帮助。

答案 2 :(得分:0)

React 16.6.0开始,我们可以lazy-load components并按需调用它们。

路由

// We pass the name of the component to load as a param
<Switch>
  …
  <Route path="/somewhere/:componentName" component={MyDynamicComponent} />
</Switch>

views / index.js

import { lazy } from 'react';

const SomeView = lazy(() => import('./SomeView'));
const SomeOtherView = lazy(() => import('./SomeOtherView'));

export { SomeView, SomeOtherView };

MyDynamicComponent.js

import React, { Suspense, Component } from 'react';
import { PropTypes } from 'prop-types';
import shortid from 'shortid'; // installed separately via NPM
import * as Views from './views';

class MyDynamicComponent extends Component {
  render() {
    const {
      match: {
        params: { componentName },
      },
    } = this.props;

    const Empty = () => <div>This component does not exist.</div>;
    const dynamicComponent = (() => {
      const MyComponent = Views[`${componentName}View`]
        ? Views[`${componentName}View`]
        : Empty;
      return <MyComponent key={shortid.generate()} />;
    })();

    return (
      <>
        <Suspense fallback={<div>Loading…</div>}>{dynamicComponent}</Suspense>
      </>
    );
  }
}
MyDynamicComponent.propTypes = {
  match: PropTypes.shape({
    params: PropTypes.shape({
      componentName: PropTypes.string.isRequired,
    }),
  }),
};

export default MyDynamicComponent;

用法

{items.map(item => (
  <NavLink to={`/somewhere/${item.componentName}`}>
    {item.name}
  </NavLink>
))}
相关问题