简体   繁体   中英

Distinguish between img & svg when passed down as a prop in React

Assume I have a component <MyComponent /> that takes in prop called src the src prop can take in svg as well as a img`

 <MyComponent src={someSvgComponent} />

Or

 <MyComponent src={someImgComponent} />

How do I check if the passed prop in src is an image or an svg? An image can be of type jpeg|jpg|png|gif

Now the src prop can either pass the file or the path of the file.

The easiest solution imo is to add a second srcType prop to MyComponent that will tell it what type of image is being passed as a prop. That's assuming that you know what image is being passed in beforehand.

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

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

Since both file src and the base 64 encoded string contains the format you can just check the following within MyComponent or else as if you know image type before hand pass it as prop to your MyComponent.

If your base 64 string is like following str.includes directly works else you guess mime type from base64 data ( data:image/type;base64, which won't contain this part).

'data:image/png;base64,iVBORw0KGgoAA...5CYII='
'data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9IjUxMn..'

Else

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM