按照本教程A Guide to Responsive Images with Ready-to-Use Templates
我发现以下问题来实现react中的组件:
解析'srcset'属性值失败,因为它有一个未知的 描述符
删除了srcset候选“XXXXXXXXXXXXXX.webp”
最终只加载标签img
的src中的图像我的反应组件如下:
/**
* Component to receive images and be responsive
*/
class RImage extends Component {
render() {
const {
lg_1x,
lg_2x,
md_1x,
md_2x,
sm_1x,
sm_2x,
lg_1x_JPG,
md_1x_JPG,
sm_1x_JPG,
} = this.props;
return (
<picture>
<source
media="(min-width: 900px)"
srcSet={`${lg_1x} 1x, ${lg_2x} 2x"`}
type="image/webp"
/>
<source
media="(min-width: 601px)"
srcSet={`${md_1x} 1x, ${md_2x} 2x"`}
type="image/webp"
/>
<source
srcSet={`${sm_1x} 1x, ${sm_2x} 2x"`}
type="image/webp"
/>
<img
srcSet={`${sm_1x_JPG} 600w,
${md_1x_JPG} 900w,
${lg_1x_JPG} 1440w`}
src={lg_1x_JPG} //This is the file that loads in the browser
type="image/jpeg"
alt="image description"
/>
</picture>
);
}
}
这里我展示了我如何使用它:
//Responsive Images
import lg_1x_JPG from '../../images/Programing/Programing-lg_1x.jpg';
import md_1x_JPG from '../../images/Programing/Programing-md_1x.jpg';
import sm_1x_JPG from '../../images/Programing/Programing-sm_1x.jpg';
//Only Chrome
import lg_1x from '../../images/Programing/Programing-lg_1x.webp';
import lg_2x from '../../images/Programing/Programing-lg_2x.webp';
import md_1x from '../../images/Programing/Programing-md_1x.webp';
import md_2x from '../../images/Programing/Programing-md_2x.webp';
import sm_1x from '../../images/Programing/Programing-sm_1x.webp';
import sm_2x from '../../images/Programing/Programing-sm_2x.webp';
class ImageClas extends Component {
render() {
return (
<Grid>
<Grid item>
<h1>Image</h1>
<p>A beautiful Image</p>
</Grid>
<Grid item>
<RImage
lg_1x={lg_1x}
lg_2x={lg_2x}
md_1x={md_1x}
md_2x={md_2x}
sm_1x={sm_1x}
sm_2x={sm_2x}
lg_1x_JPG={lg_1x_JPG}
md_1x_JPG={md_1x_JPG}
sm_1x_JPG={sm_1x_JPG}
/>
</div>
</Grid>
</Grid>
);
}
}
我认为问题在于WepPack如何导入图像文件,因为控制台发送error Dropped srcset candidate "/static/media/anyFile.webp"
,这是一个相对路径,我不确定srcSet是否需要绝对路径。
如何完成响应式图像的组件?以正确的方式工作。
答案 0 :(得分:0)
这部分代码还有一些逗号
<source
media="(min-width: 900px)"
srcSet={`${lg_1x} 1x, ${lg_2x} 2x`}
type="image/webp"
/>
<source
media="(min-width: 601px)"
srcSet={`${md_1x} 1x, ${md_2x} 2x`}
type="image/webp"
/>
<source
srcSet={`${sm_1x} 1x, ${sm_2x} 2x`}
type="image/webp"
/>
由于我已经写完了整个问题,我将离开它有两个原因,试图帮助有类似问题的人,另一个是这个组件作为寻找响应式图像的人的基础