【问题标题】:JSX get Component by stringJSX 通过字符串获取组件
【发布时间】:2017-11-03 12:21:52
【问题描述】:

这很难解释。

我从组件库中获得了几个Icons,如下所示:

import { Icons } frommy-component-library';`

假设我有 3 个图标,分别名为 IconPlus、IconMinus 和 IconEquals。

我可以轻松地显示IconEquals 以及如下描述道具:

const IconContainer = ({ description ) => (
    <div>
        {description}
        <Icons.IconEquals />
    </div>
)

这很好用。现在我正在尝试实现一个模板,我可以在其中将另一个道具 icon 传递给该容器,该容器将显示相应的图标。

例如。如果icon 是IconPlus

然后它应该呈现以下内容:

<div>
    {description}
    <Icons.IconEquals />
</div>

如何实现我的JSX 来做到这一点?

这基本上就是我所拥有的:

import { Icons } from 'my-component-library'

const IconContainer = ({ description, icon }) => (
    <div>
        {description}
        <Icons.{icon} /> // <---- Obviously that doesn't work
        // ^^^^ But I need something like this
    </div>
);

可以这样做吗?

【问题讨论】:

    标签: javascript reactjs ecmascript-6 jsx


    【解决方案1】:

    你可以这样使用:

    <Icons[icon] />
    

    【讨论】:

    • 你确定?因为这给了我一个SyntaxError: unexpected token 问题
    • @BarryMichaelDoyle,请您为此创建 plnkr/jsfiddle 吗?
    • 好吧,你把我引向了正确的方向,这很酷。我在说const Icon = Icons[icon] 之后通过渲染&lt;Icon /&gt; 来做到这一点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2014-07-26
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多