首页 > 解决方案 > React TS - 如何通过 FontAwesome 图标映射并显示它们

问题描述

我正在尝试创建一个可重用的组件,它允许我传递href, target,rel属性以及我想使用的 FontAwesome Icon 的类型。我希望能够将尽可能多的图标传递到此列表中,并且它会使用 Social 组件作为模板映射它们。

我希望地图发生在Social.tsx文件中,然后我可以简单地将组件添加到项目中的任何位置,然后将道具传递给它。

像这样的东西:

<Social
  icons={[
    { icon: "facebook", href: "", target: "", rel: "" },
    { icon: "twitter", href: "", target: "", rel: "" },
    { icon: "discord", href: "", target: "", rel: "" }
  ]}
/>

我目前有我的组件:

社交.tsx

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as React from "react";

interface ISocial {
  href?: string
  target?: string
  rel?: string
}

const Social: React.FC<ISocial> = (props) => {
  return (
    <div>
      <a href={props.href} target={props.target} rel={props.rel}>
        {/* I don't want to hardcode the icon, but dynamically pass it as a prop */}
        <FontAwesomeIcon icon={["fab", "discord"]} />
      </a>
    </div>
  );
};

export default Social;

应用程序.tsx

import * as React from "react";
import "./styles.css";
import Social from "./components/Social";

export default function App() {
  // I'd like to be able to pass in a list of different icons
  // followed by the href, target, rel, etc for each item.
  // The Social component would be able to map through them
  // and display them.
  return <Social />;

我怎样才能适应它来做我上面描述的事情?

这是一个CodeSandBox

提前感谢您的帮助!

标签: javascriptreactjstypescriptfont-awesome

解决方案


所以,我认为问题在于构建你想要传递的道具。

例如,我们将传递一个类型数组,IconProp然后您可以轻松地对其进行映射。

现在您可以制作自己的界面并传递这种类型的道具

interface myType {
  href?: string;
  target?: string;
  rel?: string;
  icon: IconProp;
}
const dummyProp: myType[] = [
  { icon: ["fab", "discord"] },
  { icon: ["fab", "discord"] },
  { icon: ["fab", "discord"] },
  { icon: ["fab", "discord"] }
];

const Social: React.FC<ISocial> = props => {
  return (
    <div>
      {dummyProp.map(p => (
        <a href={p.href} target={p.target} rel={p.rel}>
          <FontAwesomeIcon icon={p.icon} />
        </a>
      ))}
    </div>
  );

推荐阅读