簡體   English   中英

ReactJS-更改圖像onMouseOver不起作用

[英]ReactJS - changing image onMouseOver does not work

我的目標是創建一個無狀態的圖像按鈕組件,當我將鼠標懸停在其上時可以更改圖像,以后可以在其他地方使用。

我當前的問題是,在調用onMouseOver事件時,無法設置“懸停”圖像。 圖片未顯示,看起來像這樣:

在此處輸入圖片說明

// Assets
import image from '../assets/normal.png';
import imageSelected from '../assets/selected.png';

const HoverImage = () => {
  function over(e) {
    e.currentTarget.src = { imageSelected };
  }
  function out(e) {
    e.currentTarget.src = { image };
  }
  return <img src={image} onMouseOver={over} onMouseOut={out} />;
};

export default HoverImage;

當我沒有將鼠標懸停在組件上時,圖像將正確顯示。 我在做錯什么或如何改進代碼以實現目標?

另外,我也不想在CSS中使用硬編碼的圖像路徑。 最好的辦法是通過我猜想的道具設置圖像。

只需在imageSelectedimage周圍刪除{} ,實際上在這些對象周圍插入{}傳遞對象,而不是圖像。

import image from '../assets/normal.png';
import imageSelected from '../assets/selected.png';

const HoverImage = () => {
  function over(e) {
    e.currentTarget.src =  imageSelected ;
 }
  function out(e) {
    e.currentTarget.src =  image ;
  }
    return <img src={image} onMouseOver={over} onMouseOut={out} />;
   };

 export default HoverImage;

對於第二個問題,您可以將圖像作為道具傳遞並像這樣顯示:

 const HoverImage = props => {
 function over(e) {
  e.currentTarget.src = props.hoverImage;
}
 function out(e) {
   e.currentTarget.src = props.normalImage;
}
return <img src={props.normalImage} onMouseOver={over} onMouseOut={out} />;
};

您可以檢查此Sandboox以獲取更多信息;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM