我导入了两种图像( IMG 和 IMG2 )。 IMG 假设在视口宽度小于 600px 时显示,而如果视口宽度大于或等于 600px,则显示另一张。所以我添加了一个函数来检查视口宽度,然后它返回这两个图像之一,但问题是它只返回我放入函数中的第一个图像,即 IMG。即使视口宽度变得大于 600px,它仍然显示 IMG 而不是 IMG2。注意:我可以通过仅使用媒体查询并将显示设置为无来解决此问题,但我想知道如何使用 React 来解决此问题。
链接到我在 Github 中的所有代码: https://github.com/Issamath/PerfumeProduct.com
import IMG from '../../assets/image-product-mobile.jpg'
import IMG2 from '../../assets/image-product-desktop.jpg'
const ProductImage = () => {
  function displayImage(){
    let vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
    console.log(vw);
    if(vw < 600) {
     console.log(vw + "is smaller than 600");
     return (<img src={IMG} alt="" />);
    } else {
     console.log(vw + "is bigger than 600");
     return (<img src={IMG2} alt="" />);
    }
}
  return (
    <div className='container-img'>
      {displayImage()}
    </div>
  )
}
export default ProductImage
.container-img img {
    height: 15rem;
    width: 100%;
    background: white;
    border-radius: 0.8rem 0.8rem 0 0;
}
.container-img {
   
}
 /* -----------------for bigger phones------------------- */
@media screen and (min-width: 390px) {
    .container-img img {
        height: 20rem;
    }
}            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
要使用 React 执行此操作,您需要附加到文档调整大小事件。
下面是一个简单的示例,在调整大小时更改文本和背景颜色。
const {useEffect, useState} = React; const getWidth = () => document.documentElement.clientWidth; const ResizeCheck = () => { const [width, setWidth] = useState(getWidth()); useEffect(() => { const resize = () => setWidth(getWidth()); window.addEventListener('resize', resize); return () => window.removeEventListener('resize', resize); }, []); return{
    width >= 600 
      ? Greater than equal to 600 
      : Less than 600 
    }
   ;
}
const root = ReactDOM.createRoot(document.querySelector('#mount'));
root.render( );