代码之家  ›  专栏  ›  技术社区  ›  Adeel Imran

在React中作为道具传递时区分img和svg

  •  2
  • Adeel Imran  · 技术社区  · 6 年前

    <MyComponent /> that takes in prop called src公司 the prop can take in as well as a

     <MyComponent src={someSvgComponent} />
    

    或者

     <MyComponent src={someImgComponent} />
    

    如何检查道具是否通过 src

    现在 src公司 prop可以传递文件或文件的路径。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Chase DeAnda    6 年前

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

    <MyComponent src={someSvgComponent} srcType="svg" />
    
    <MyComponent src={someImgComponent} srcType="img" />
    
        2
  •  1
  •   Shubham Gupta    6 年前

    由于文件src和base64编码字符串都包含格式,您可以在MyComponent中检查以下内容,或者在手动将图像类型作为prop传递给MyComponent之前,就好像您知道图像类型一样。

    data:image/type;比较基准64, 不包含此部分)。

    '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
    }