【问题标题】:Distinguish between img & svg when passed down as a prop in React在 React 中作为道具传递时区分 img 和 svg
【发布时间】:2018-09-24 16:33:18
【问题描述】:

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

 <MyComponent src={someSvgComponent} />

或者

 <MyComponent src={someImgComponent} />

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

现在src 属性可以传递文件或文件的路径。

【问题讨论】:

  • 文件是指 base 64 编码的 svg/img 数据?
  • 是的,我的意思是文件。

标签: javascript reactjs svg


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    由于文件 src 和 base 64 编码字符串都包含格式,您可以在 MyComponent 中检查以下内容,否则就好像您事先知道图像类型一样将其作为道具传递给您的 MyComponent。

    如果您的 base 64 字符串类似于 str.includes 直接工作,否则您会从 base64 数据中猜测 mime 类型(data:image/type;base64, 不包含此部分)。

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

    【讨论】:

    • can either pass the file or the path of the file. 意味着它并不总是带有扩展名的字符串文件名。它还需要支持base64字符串。
    • @ChaseDeAnda 编辑了答案,看看现在是否更有意义。
    猜你喜欢
    • 2020-10-19
    • 2018-02-28
    • 2018-08-01
    • 2020-02-18
    • 2023-03-12
    • 2016-04-29
    • 2019-05-02
    • 1970-01-01
    • 2020-11-17
    相关资源
    最近更新 更多