首页 > 解决方案 > 在 React 中作为道具传递时区分 img 和 svg

问题描述

假设我有一个组件<MyComponent /> that takes in prop calledsrc thesrc prop can take insvg as well as aimg`

 <MyComponent src={someSvgComponent} />

或者

 <MyComponent src={someImgComponent} />

如何检查传入的道具src是图像还是svg?图像可以是 jpeg|jpg|png|gif 类型

现在srcprop 可以传递文件或文件的路径。

标签: javascriptreactjssvg

解决方案


imo 最简单的解决方案是添加第二个srcType道具MyComponent,它将告诉它作为道具传递的图像类型。这是假设您事先知道传入的是什么图像。

<MyComponent src={someSvgComponent} srcType="svg" />

<MyComponent src={someImgComponent} srcType="img" />

推荐阅读