【问题标题】:get components by string names in ReactJS在 ReactJS 中通过字符串名称获取组件
【发布时间】:2018-04-23 07:12:52
【问题描述】:

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

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,并返回组件对象。

现在我正在使用 switch case 来执行此操作,但组件太多,而且我的源代码很乱。有没有办法在reactJS中通过字符串名称获取值?例如:

returnChild = (childName) => {
    return get_value_by_name(childName)
} 

【问题讨论】:

  • 你能详细说明你为什么需要这个字符串吗?添加你的Main 代码。

标签: reactjs jsx react-component


【解决方案1】:

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

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,  
    ....
}

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

returnChild = childName => STRING_TO_COMPONENTS[childName];

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

【讨论】:

  • 没有。我不想重复名称。我想让它动态
  • 这是动态的,您不会创建重复的名称。您只是在制作一个“动态”将为您提供组件的对象。另外,如果您发现更好的解决方案,请发表评论。
  • 我没有找到任何好的解决方案。对于“动态”,我是指将新组件添加到组件目录时。我不必多次命名它的名字
  • 因为没有更好的解决方案。如果有,有人会回答你的问题:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-20
  • 2013-02-11
相关资源
最近更新 更多