React 组件内部函数的意外输出
P粉614840363
P粉614840363 2024-04-03 00:17:44
[CSS3讨论组]

我导入了两种图像( IMGIMG2 )。 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;
    }
}

P粉614840363
P粉614840363

全部回复(1)
P粉401901266

要使用 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();
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号