javascript - 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
提前感谢您的帮助!
解决方案
所以,我认为问题在于构建你想要传递的道具。
例如,我们将传递一个类型数组,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>
);
推荐阅读
- python - 如何将套接字添加到 listWidget
- oauth-2.0 - OAuth2、API 和 JavaScript 应用程序 - 令牌验证服务器端还是客户端?
- javascript - 当位置是相对时,可拖动元素会更改其边距
- umd - Parceljs 构建 UMD
- ios - NavigationController Push 不工作 ios 11
- c++ - 如何 const 映射变量
- amazon-web-services - 为什么我的 EC2 Auto Scaling 组在增长?
- api - Twitter API 不返回所有关注者,即使使用光标和避免速率限制
- php - 为什么从前端更新元需要我得到旧值?
- db2 - 如何禁用旧应用程序使用 XA 数据源?