首页 > 解决方案 > 在没有 srcset 的情况下反应响应式图像?

问题描述

我想确认 React 是否能够在不需要 html 中的 srcset 标签的情况下提供响应式图像。

使用带有窗口宽度的状态,我可以设置图像的条件渲染。使用 chrome 并检查网络流量,似乎正在提供所需的图像,而无需提供所有图像。

import React from "react"
import images from "../assets/images"


class App extends React.Component{
    state = {
        width: 0
    }
    componentDidMount(){
        window.addEventListener("resize", this.handleResize)
        this.setState({
            width: window.innerWidth
        })
        console.log(this.state.width)
    }
    handleResize = () =>{
        this.setState({
            width: window.innerWidth
        })
        console.log(this.state.width)
    }
    render(){
        const image = this.state.width > 1000 && this.state.width !== 0 ? images.HD : images.LD
        return(
            <div>
                <img src={image} alt="hd/ld"/>
            </div>
        )
    }
}

export default App

这是提供具有不同分辨率的特定图像的有效方法吗?

标签: htmlreactjs

解决方案


推荐阅读