当为网页某个功能导入图标时,我们通常会选择直接导入svg文件。
但是有时候需要根据不同的状态来改变图标的颜色或者其他样式,可能有些人会选择导入多个svg文件,再通过条件判断来决定渲染哪一个。
比如以下这种情况,根据点赞数countLikes变化,来决定渲染哪种颜色的图标。
import IconRed from '../icon-red.svg';
import IconGreen from '../icon-red.svg';
import IconBlue from '../icon-red.svg';
interface IProps {
countLikes: number;
}
export default function Post(props, IProps) {
const { countLikes } = props;
const chooseIcon = () => {
if (countLikes < 10) return IconRed;
if (countLikes < 20) return IconGreen;
if (countLikes < 30) return IconBlue;
}
return (
<div>
<img src={chooseIcon()} alt="alt" />
</div>
)
}
但如果有十几个图标需要导入的时候,写十几行import不太好,所以这不是最好的方法。
此文介绍用组件形式导入图标的方法,只需要导入一个,便能使其具有可定制性。
-
首先,决定好你要用的图标,找到对应的svg code。对于本例,我们去Remix Icon找到一个爱心图标。
-
点击"Copy SVG"并打开React-SVGR (一个能将svg code转换成react组件代码的工具)将svg code粘贴进去,把生成的react组件代码复制,放进我们的新建文件LikeIcon.tsx里。
export default function LikeIcon({ color }: { color: string }) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" {...props}>
<path d="M12.001 4.529a5.998 5.998 0 0 1 8.242.228 6 6 0 0 1 .236 8.236l-8.48 8.492-8.478-8.492a6 6 0 0 1 8.48-8.464Z" />
</svg>
)
}
- 在Post组件里导入LikeIcon组件
import LikeIcon from './LikeIcon'
interface IProps {
countLikes: number;
}
export default function Post(props, IProps) {
const { countLikes } = props;
const chooseColor = () => {
if (countLikes < 10) return "red";
if (countLikes < 20) return "green";
if (countLikes < 30) return "Blue";
}
return (
<div>
<LikeIcon color={chooseColor()} />
</div>
)
}