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)作为构建系统。
最佳答案
我不知道 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]
关于javascript - 如何将字符串转换为类名(不在窗口上定义它)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38758274/