[英]React Rendering Component React-Icons
How to render component based on json file information?如何根据json文件信息渲染组件? I have a map that is rendering a UL list.
我有一张渲染 UL 列表的地图。 Each Li is rendered.
每个 Li 都被渲染。 (I know i can do this with a img and than passing src={} as a object from the json file. But i wanna know if there's another way of solving this. Code below:
(我知道我可以用 img 来做到这一点,而不是将 src={} 作为来自 json 文件的对象传递。但我想知道是否有另一种方法来解决这个问题。下面的代码:
import React from 'react'
import { FiLinkedin as LinkedinIcon, FiGithub as GithubIcon } from 'react-icons/fi';
import Data from '../../socials.json';
import { Container } from './styles';
export default function Profile() {
return (
<Container>
<ul id="profile-links">
{Data.map((social, index) => {
return (
<li id={social.id} key={social.id}>
<a href={social.url} target="_BLANK" rel="noreferrer">
<LinkedinIcon size={22} /> // change this component based on -social.icon info-
<strong>{social.title}</strong>
<span className="small-link">{social.slug}</span>
</a>
</li>
)
})}
</ul>
</Container>
)
}
I would convert your socials.json
into a socials.js
.我会将您的
socials.json
转换为socials.js
。 Then you can set up your data more flexibly like this:然后你可以像这样更灵活地设置你的数据:
import {
FiLinkedin as LinkedinIcon,
FiGithub as GithubIcon,
} from 'react-icons/fi';
const Data = [
{
id: 1,
url: 'url 1',
title: 'title 1',
slug: 'slug 1',
icon: LinkedinIcon,
},
// Other socials...
];
export default Data;
Then you can render these icons dynamically in your map like this:然后你可以在你的地图中动态渲染这些图标,如下所示:
// ...
import Data from '../../socials';
export default function Profile() {
return (
<Container>
<ul id="profile-links">
{Data.map((social, index) => {
return (
<li id={social.id} key={social.id}>
<a href={social.url} target="_BLANK" rel="noreferrer">
<social.icon size={20} />
<strong>{social.title}</strong>
<span className="small-link">{social.slug}</span>
</a>
</li>
);
})}
</ul>
</Container>
);
}
You can create a method which will give you the icon depending on the social.icon
value.您可以创建一个方法,根据
social.icon
值为您提供图标。 For example:例如:
const getIcon = (icon) => {
switch(icon) {
case A:
return <IconA />;
case B:
return <IconB />;
default:
return null;
}
}
And call this getIcon method where you need it with the social.icon
as params.并在需要的地方调用此 getIcon 方法,并将
social.icon
作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.