【问题标题】:How to import a component or file in React using variables?如何使用变量在 React 中导入组件或文件?
【发布时间】:2017-11-01 20:39:05
【问题描述】:

我正在使用 React 构建一个 Web 应用程序,它显示了您在已选择的校园中选择的建筑物的蓝图。

我有一个“内容”组件,用于加载校园或建筑地图,具体取决于您的选择。 “BuildingMap”组件需要根据您选择的建筑物加载特定的蓝图。它获取带有建筑物名称的 props.building,但我不知道如何使用该变量加载组件。

我尝试过 import、fetch 和 require,但似乎没有任何效果。

请帮忙。

我的代码如下所示:

//内容组件

<BuildingMap building={selectedBuilding} campus={selectedCampus} />

//建筑地图组件

import *MyBlueprint* from (specific folder depending on the campus selected)

class BuildingMap extends React.Component {
  render(){
    return (
      <div className="blueprint" id={this.props.building}>
         {*MyBlueprint*}
      </div>
    )
  }
}

【问题讨论】:

  • 是否需要在运行时加载模块,而不是将组件打包到对象中并通过键引用它们?后者更为常见。

标签: reactjs variables import components require


【解决方案1】:

很遗憾,您不能在 React 环境中动态导入/需要组件。

根据建筑物/蓝图的数量,可以一一导入,创建组件构建图,通过建筑物ID选择组件。

如果要加载许多/无限的组件,我肯定会选择另一种方法 - 不知道您的问题的内容。

import BlueprintA from './BlueprintA'
import BlueprintB from './BlueprintB'
import BlueprintC from './BlueprintC'
// ...

class BuildingMap extends React.Component {
  render(){
    const C = {
      buildingA: BlueprintA,
      buildingB: BlueprintB,
      buildingC: BlueprintC,
      // ...
    }[this.props.building]

    return (
      <div className="blueprint" id={this.props.building}>
         <C />
      </div>
    )
  }
}

【讨论】:

  • 动态加载模块是可能的,但对于这种情况肯定更罕见,您的解决方案在 99% 的情况下都很好。我还将对象构造放在组件之外,以防它可以在其他地方使用。一个不错的选择可能是import * as blueprints from ..
  • 好吧,我的意思是不可能动态导入/需要模块 - 通过变量的值,例如导入所有命名模块是这里的选项。感谢您提及:)
  • 可以动态地请求模块,尽管使用变量名。例如:github.com/NCI-GDC/portal-ui/blob/relay/src/packages/%40ncigdc/…
  • 抱歉这个菜鸟问题,但这是什么意思? const C = { buildingA: BlueprintA, // ... }[this.props.building]最后一点没看懂,[this.props.building]是什么意思?
【解决方案2】:

添加到@Andreyco 的答案:

对组件类使用字符串 ID/名称的查找表是一个典型的 React 习惯用法。一个常见的用例是模态管理器组件,它可以呈现多种不同类型的模态。有关示例,请参阅 Dan Abramov 在 "How can I render a modal dialog in Redux?" 的回答(不是 Redux 特定的),以及我的 React/Redux links listReact Component Patterns#Modal DialogsRedux Techniques#UI 部分中的一些相关文章。

根据@azium 的评论:绝对可以使用动态导入(通过require.ensure() 或新的import() 函数)在运行时加载块,您可以将这些动态导入块的导出添加到查找表中当它们被加载时。

【讨论】:

    【解决方案3】:

    这个问题已经很老了,但是当我在寻找如何解决同样的问题时,让我给出我的答案。可以通过动态导入 React.lazy 来完成:

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

    在此处查看更多详细信息:https://reactjs.org/docs/code-splitting.html#reactlazy

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 2022-01-02
      • 2019-04-06
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多