首頁  >  問答  >  主體

React 元件內部函數的意外輸出

我導入了兩個映像( 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粉614840363P粉614840363180 天前299

全部回覆(1)我來回復

  • P粉401901266

    P粉4019012662024-04-03 10:46:34

    要使用 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();
    sssccc
    sssccc
    
    

    回覆
    0
  • 取消回覆