gpt4 book ai didi

reactjs - react : render concatenated component based on imported list of components

转载 作者:行者123 更新时间:2023-12-03 13:44:12 25 4
gpt4 key购买 nike

我不确定我正在尝试做的事情是否可能,或者是否有更好的方法来实现我的目标。任何见解都会非常有帮助。

上下文:

  • 我有一个充满渲染内联 SVG 组件的目录
  • 这些组件聚集在 IconsIndex.js 中文件并导出如下:

export { default as Rocket } from "./Rocket";

  • 我正在导入索引,以便从任何给定组件访问我的图标库:

import * as Icon from "./icons/IconsIndex";

这基本上让我可以做:<Icon.Rocket />它完美地呈现了 SVG 组件。

我想做的是能够拥有 <Icon />组件能够从父组件变得更加动态。

例如:

class ResourceBlock extends React.Component {
render() {
return (
<BlockContainer>
<BlockIcon>
<Icon.Rocket />
</BlockIcon>
<BlockTitle>{this.props.caption}</BlockTitle>
<Button>{this.props.buttonText}</Button>
</BlockContainer>
);
}
}

这会输出Rocket图标无处不在ResourceBlock组件被调用。我希望能够做的是这样的:

<ResourceBlock icon={Icon.Rocket} caption="Lorem..." buttonText="..." />

这可能吗?如何使用我们的图标实现这种级别的灵 active ?

关键是让 SVG 尽​​可能解耦,因此将它们全部包装在一个额外的 <Icon /> 中。组件没有吸引力。

最佳答案

这有点奇怪,但是 in JSX if the node name is lowercase it will be translated as an html tag ,不是组件引用。因此,只需将您的图标属性分配给大写的本地常量并以这种方式呈现它:

class ResourceBlock extends React.Component {
render() {
const Icon = this.props.icon;
return (
<BlockContainer>
<BlockIcon>
<Icon />
</BlockIcon>
<BlockTitle>{this.props.caption}</BlockTitle>
<Button>{this.props.buttonText}</Button>
</BlockContainer>
);
}
}

就像您拥有它一样使用:

<ResourceBlock icon={Icon.Rocket} caption="Lorem..." buttonText="..." />

关于reactjs - react : render concatenated component based on imported list of components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47657588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com