[英]Image not loading when passing a prop to <img src=“this.prop.” /> in React
[英]Distinguish between img & svg when passed down as a prop in React
假设我有一个组件<MyComponent /> that takes in prop called
src the
prop can take in
the
src prop can take in
svg as well as a
img。
<MyComponent src={someSvgComponent} />
要么
<MyComponent src={someImgComponent} />
如何检查src
传递的prop是图像还是svg? 图片可以是jpeg | jpg | png | gif类型
现在, src
属性可以传递文件或文件的路径。
imo的最简单解决方案是在MyComponent
中添加第二个srcType
,该srcType
将告诉它正在传递哪种类型的图像作为srcType
。 假设您事先知道要传递什么图像。
<MyComponent src={someSvgComponent} srcType="svg" />
<MyComponent src={someImgComponent} srcType="img" />
由于文件src和以64为基数的编码字符串都包含格式,因此您可以仅在MyComponent中检查以下内容,否则就好像您知道图像类型一样,然后将其作为道具传递给MyComponent。
如果您的base 64字符串像直接跟随str.includes一样工作,则可以从base64数据( data:image / type; base64,其中不包含此部分)中猜测mime类型。
'data:image/png;base64,iVBORw0KGgoAA...5CYII='
'data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjUxMn..'
其他
function guessImageMime(data){
if(data.charAt(0)=='P'){
return "svg";
} else if(data.charAt(0)=='/'){
return "jpeg";
} else if(data.charAt(0)=='R'){
return "gif";
} else if(data.charAt(0)=='i'){
return "png";
}
}
if(this.props.src.includes('svg') || guessImageMime(this.props.src) === 'svg') {
//it is svg
} else {
//it is image in other format
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.