首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ReactJS中按字符串名称获取组件

问在ReactJS中按字符串名称获取组件
EN

Stack Overflow用户
提问于 2018-04-23 15:12:52
回答 1查看 430关注 0票数 0

我有一个组件,其中导入了一些其他组件,例如:

代码语言:javascript
复制
import ComponentA from './components/ComponentA.js';
import ComponentB from './components/ComponentB.js';
import ComponentC from './components/ComponentC.js';
class Main extends Component {
...

然后,我在主组件内有一个名为returnChild(String childName)的函数,该函数获取字符串输入,例如ComponentA或ComponentB,并返回组件对象。

现在我使用一个开关案例来做这件事,但是组件太多了,而且我的源码也很混乱。有没有办法在reactJS中通过字符串名称获取值?例如:

代码语言:javascript
复制
returnChild = (childName) => {
    return get_value_by_name(childName)
} 
EN

回答 1

Stack Overflow用户

发布于 2018-04-23 15:37:07

您可以对组件进行配置,然后根据配置返回组件。例如,

代码语言:javascript
复制
import ComponentA from './components/ComponentA.js';
import ComponentB from './components/ComponentB.js';
import ComponentC from './components/ComponentC.js';
....

const STRING_TO_COMPONENTS = {
    'componentA': componentA,  //the key is a string and value is a component object
    'componentB': componentB,  
    'componentC': componentC,  
    ....
}

在使用时,您可以像这样使用它

代码语言:javascript
复制
returnChild = childName => STRING_TO_COMPONENTS[childName];

这将是我所知道的最好的方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49975315

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档