如何在ReactJ中渲染SVG列表
我有一个表情符号,每个表情符号都有表情符号
和label
字段。我想知道如何使用组件中的地图渲染表情符号。
我已经将所有表情符号作为SVG文件存储在src/Assets/emojiicons
中。
现在,我这样做是这样的:
import { ReactComponent as Coin } from "../assets/emojiIcons/coin.svg"
import { ReactComponent as Rocket } from "../assets/emojiIcons/rocket.svg"
const DEFAULT_EMOJI_OPTIONS = [
{
emoji: Rocket,
label: "rocket",
},
{
emoji: Coin,
label: "coin",
},
]
export { DEFAULT_EMOJI_OPTIONS }
在这样的组件中导入表情符号:
import { DEFAULT_EMOJI_OPTIONS } from "../../utils/emojis"
const EmojiSection = () => {
return (
<div className="text-white border-2 border-gray-800 rounded p-3 my-8 max-w-xs mx-auto">
{DEFAULT_EMOJI_OPTIONS.map((emoji) => (
<emoji.emoji />
))}
</div>
)
}
有什么更好的方法吗?
I have an array of emojis and each emoji has emoji
and label
field. I would like to know how to render emoji using map in my component.
I have stored all the emojis as SVG files in the src/assets/emojiIcons
.
Right now, I'm doing like this:
import { ReactComponent as Coin } from "../assets/emojiIcons/coin.svg"
import { ReactComponent as Rocket } from "../assets/emojiIcons/rocket.svg"
const DEFAULT_EMOJI_OPTIONS = [
{
emoji: Rocket,
label: "rocket",
},
{
emoji: Coin,
label: "coin",
},
]
export { DEFAULT_EMOJI_OPTIONS }
importing the emojis in my component like this:
import { DEFAULT_EMOJI_OPTIONS } from "../../utils/emojis"
const EmojiSection = () => {
return (
<div className="text-white border-2 border-gray-800 rounded p-3 my-8 max-w-xs mx-auto">
{DEFAULT_EMOJI_OPTIONS.map((emoji) => (
<emoji.emoji />
))}
</div>
)
}
Is there any better way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信
导入{ReactComponent作为COIN}
语法仅在您使用Create-react-app时起作用。如果您是,那么这可能是最好的选择,只要您不需要重新彩色图像或任何喜欢的东西。如果您不使用Create-react-app,我将只使用
img
标签。您可以使用
file-Loader
导入SVG,而不是需要将路径保留在字符串中。在您的WebPack配置中(Vite或其他系统有类似的选项):
I believe the
import { ReactComponent as Coin }
syntax only works if you're using create-react-app. If you are, then this is probably the best option, provided you don't need to re-colour the image or anything fancy like that.If you're not using create-react-app, I'd just use an
img
tag.You can use
file-loader
to import the svg, rather than needing to keep the path in a string.In your webpack config (there are similar options for vite or other systems):
我没有这两个SVG,所以我尝试使用字符串值。您可以在一个组件中映射,然后实际上可以渲染组件。您正在使用SVG作为组件。尽管此SVG是图像,但它们没有任何导出功能。在React中,您可以在标签的帮助下轻松地绘制所有SVG。
I don't have this two svg so i tried with string value. You can map in one component then you can actually render the component. You are using svg as component . While this svgs are images they don't have any export function. In react you easily map all the svgs with the help of tag.
如果您的应用程序正在使用MUI,则可以通过Svgicon对此进行核对。
如果要使用IMG,则可以通过两种方式存档。
或者
If your application is using Mui, you can archieve this by SvgIcon.
If you want to use img, you can archive by two ways.
or