一直在寻找一种方法来正确地渲染组件中的图标,但最终出现了标题错误。
Profile.tsx:
<ul>
{socialLinks.map((socialLink) => (
<li key={socialLink.href}>
<a href={socialLink.href}>{socialLink.icon}</a>
</li>
))}
</ul>
data.ts
import { FaDiscord, FaGithub, FaTwitter } from "react-icons/fa";
export const socialLinks = [
{
name: "github",
href: "#",
icon: FaGithub,
},
{
name: "twitter",
href: "#",
icon: FaTwitter,
},
{
name: "discord",
href: "#",
icon: FaDiscord,
},
];
有办法解决这个问题吗?
icon
是功能组件。你必须调用它。
或者,直接在数据配置中调用它:
{ icon: <FaGithub />, name: ..., href: ... }
或映射时:
{socialLinks.map((socialLink) => {
const Icon = socialLink.icon;
return (
<li key={socialLink.href}>
<a href={socialLink.href}>
<Icon />
</a>
</li>
);
))}
您应该能够将socialLinks.icon
重新分配给一个新变量,然后在tsx文件中将其呈现为React组件。我认为以下应该有效:
<ul>
{socialLinks.map((socialLink) => {
const Icon = socialLink.icon
return (
<li key={socialLink.href}>
<a href={socialLink.href}><Icon/></a>
</li>
))}}
</ul>