我的问题听起来可能令人困惑,坦率地说,的确如此。我试图做的是一个组件,稍后使用在多个不同的位置。该组件是一张带有图标、文本和按钮的卡片。我在字典中拥有的都是我将在这个项目中使用的所有可能的图标。我不知道该怎么做。我正尝试推行“干”原则,所以我要这样做。我想要一个卡,可以导入,然后有一些变量,将添加图标,文字和按钮。
下面是我的代码。
import React from "react";
import Button from "../Button/Button";
import { IoAppsSharp } from "react-icons/io5";
import { ImDisplay } from "react-icons/im";
import { AiFillSignal } from "react-icons/ai";
import { MdPhoneInTalk } from "react-icons/md";
import { GrCode } from "react-icons/gr";
import { MdSecurity } from "react-icons/md";
import { IoMdSchool } from "react-icons/io";
const iconDict = {
iconOne: <IoAppsSharp />,
iconTwo: <ImDisplay />,
iconThree: <AiFillSignal />,
iconFour: <MdPhoneInTalk />,
iconFive: <GrCode />,
iconSix: <MdSecurity />,
iconSeven: <IoMdSchool />
}
const Card = ({ icon, title, text, button }) => {
const checkIcon = iconDict.includes(icon) ? icon : iconDict.iconOne;
return (
<a
href="Bespoke Software"
className="card"
>
<div className="card__icon-container">
<IoAppsSharp className="card__icon-container--icon" />
</div>
<div className="card__text-container">
<h2>Bespoke Software</h2>
<p>
Tailored software solutions to improve business productivity and
online profits.
</p>
<br />
</div>
<div className="card__button-container">
<Button>Read More</Button>
</div>
</a>
);
}
export default Card;发布于 2022-10-04 15:20:38
关于您的标题:
如何用变量替换Import?
你不能像这样参数化模块,但好消息是你不需要解决你的问题。:-)
相反,我们可以这样解决它:让Card本身直接接受图标,而不是图标的名称,然后(可选地)使用高阶分量 (HOC)创建接受名称的Card版本(使用给定的字典)。
新的Card
import React from "react";
import Button from "../Button/Button";
const Card = ({ checkIcon, title, text, button }) => {
return (
<a href="Bespoke Software" className="card">
<div className="card__icon-container">
<IoAppsSharp className="card__icon-container--icon" />
</div>
<div className="card__text-container">
<h2>Bespoke Software</h2>
<p>
Tailored software solutions to improve business productivity and online profits.
</p>
<br />
</div>
<div className="card__button-container">
<Button>Read More</Button>
</div>
</a>
);
};直接使用Card:
<Card checkIcon={<IoAppsSharp/>} {/*...*/} />
// Or keep using `iconDict`:
<Card checkIcon={iconDict.iconOne} {/*...*/} />特别报告员:
function withIcons(Card, iconDict) {
return ({icon, ...rest}) => {
const checkIcon = iconDict.includes(icon) ? icon : iconDict.default; // Note I changed the name of the default
return <Card checkIcon={checkIcon} {...rest} />;
};
}利用特设:
const iconDict = {
iconOne: <IoAppsSharp />,
iconTwo: <ImDisplay />,
iconThree: <AiFillSignal />,
iconFour: <MdPhoneInTalk />,
iconFive: <GrCode />,
iconSix: <MdSecurity />,
iconSeven: <IoMdSchool />,
};
const CardWithCertainIcons = withIcons(Card, iconDict);使用该组件:
<CardWithCertainIcons icon="iconOne" {/*...*/ />如果是临时的,请参阅链接较早获得有关它们的一些重要信息,推荐和静态方法等等。
https://stackoverflow.com/questions/73949913
复制相似问题