为什么 React.js 删除 <img /> 上的 srcset 标签?

IT技术 html reactjs srcset
2021-05-24 11:32:28

当我的标签srcset有该属性时<img />,为什么它不显示在浏览器中?它似乎通过 React.js 正在剥离它。

<img src="/images/logo.png" srcset="/images/logo-1.5x.png 1.5x, /images/logo-2x.png 2x" />
3个回答

解决方案是使用srcSet而不是srcset.

<img src="/images/logo.png" srcSet="/images/logo-1.5x.png 1.5x, /images/logo-2x.png 2x" />

参考:https : //facebook.github.io/react/docs/tags-and-attributes.htmlHTML Attributes

另一个使用模板文字的丑陋解决方案:

<img
  alt=''
  src={require('../../assets/images/logo/logo.png')}
  srcSet={`
    ${require('../../assets/images/logo/logo@2x.png')} 2x, 
    ${require('../../assets/images/logo/logo@3x.png')} 3x
  `}
/>

尝试将 srcSet 与字符串一起使用对我不起作用,可能是因为 Webpack 最终是如何工作的,因此导入它们并将它们包含在模板字符串中,如下例所示:

import nat1 from "./img/nat-1.jpg";
import nat1Large from "./img/nat-1-large.jpg";
import nat2 from "./img/nat-2.jpg";
import nat2Large from "./img/nat-2-large.jpg";
import nat3 from "./img/nat-3.jpg";
import nat3Large from "./img/nat-3-large.jpg";


  <div className="composition">
                <img
                  srcSet={`${nat1} 300w, ${nat1Large} 1000w`}
                  sizes="(max-width: 56.25em) 20vw, (max-width: 37.5em) 30vw, 300px"
                  alt="Photo 1"
                  className="composition__photo composition__photo--p1"
                  src={nat1Large}
                />
                <img
                  srcSet={`${nat2} 300w, ${nat2Large} 1000w`}
                  sizes="(max-width: 56.25em) 20vw, (max-width: 37.5em) 30vw, 300px"
                  alt="Photo 2"
                  className="composition__photo composition__photo--p2"
                  src={nat2Large}
                />
                <img
                  srcSet={`${nat3} 300w, ${nat3Large} 1000w`}
                  sizes="(max-width: 56.25em) 20vw, (max-width: 37.5em) 30vw, 300px"
                  alt="Photo 3"
                  className="composition__photo composition__photo--p3"
                  src={nat3Large}
                />
  </div>