如何将字符串转换为类名(不在窗口中定义)?

时间:2016-08-04 03:59:51

标签: javascript reactjs ecmascript-6 brunch es6-module-loader

import TestClass from './TestClass'

如果给定字符串TestClass

,如何在此文件中引用'TestClass'

eval('TestClass')无效,因为TestClass is not defined

但是,如果我执行let Test = TestClass,然后eval('Test'),则会根据需要返回TestClass的构造函数。

eval('TestClass')为什么eval('Test')不起作用?

上下文: 鉴于<div data-class="TestClass"></div>等许多元素,我想创建一个通用函数,将适当的React组件呈现给它们。在执行此函数之前,这些组件类将被导入到文件中。

注意:使用Brunch(类似于webpack)作为构建系统。

1 个答案:

答案 0 :(得分:2)

我不知道Brunch做了什么,但你可以在导入后用组件创建一个对象,并使用它来检索给定字符串的组件。类似的东西:

import TestClass1 from './TestClass1'
import TestClass2 from './TestClass2'

const componentMap = {
  TestClass1: TestClass1,
  TestClass2: TestClass2
}

// You can just use the map to get the component given the name
const component = componentMap[componentName]