我正在 React 中構建一個燈箱,它回圈遍歷一組物件,但我似乎無法同時顯示影像和文本。最終,我希望每張圖片上都有文字,只是為了識別每種害蟲。
錯誤是我在頁面上得到空物件。我確信我在做一些非常愚蠢的事情;)
[object Object]
可能有人對如何使這項作業有任何見解,或者我是否缺少某些東西?提前致謝。
import { useState } from 'react';
import Ant from '../../img/ant.jpeg';
import Bee from '../../img/bee.jpeg';
import Bedbug from '../../img/bedbug.jpeg';
import Wasp from '../../img/wasp.jpeg';
import Mouse from '../../img/mouse.jpeg'
// const images = [Bee, Ant, Bedbug, Wasp, Mouse];
const images_arr = [
{ image: Ant, text: "Ant" },
{ image: Bee, text: "Bee" },
{ image: Bedbug, text: "Bedbug" },
{ image: Mouse, text: "Mice" },
{ image: Wasp, text: "Wasp" },
]
console.log(images_arr)
function PestsGallery() {
const [imageToShow, setImageToShow] = useState("");
const [lightboxDisplay, setLightBoxDisplay] = useState(false);
//looping through our images array to create img elements
const imageCards = images_arr.map((image, text) => (
<img key={image} alt={image} className="image-card" onClick={() => showImage(image)} src={image} />
));
const showImage = (image, text) => {
setImageToShow(image);
setLightBoxDisplay(true)
}
const hideLightBox = () => {
setLightBoxDisplay(false)
}
const showNext = (e) => {
e.stopPropagation();
let currentIndex = images_arr.indexOf(imageToShow);
if (currentIndex >= images_arr.length - 1) {
setLightBoxDisplay(false)
} else {
let nextImage = images_arr[currentIndex 1];
setImageToShow(nextImage)
}
}
const showPrev = (e) => {
e.stopPropagation();
let currentIndex = images_arr.indexOf(imageToShow);
if (currentIndex <= 0) {
setLightBoxDisplay(false);
} else {
let nextImage = images_arr[currentIndex - 1];
setImageToShow(nextImage);
}
};
這是回傳陳述句和其余部分
return (
<>
<h2> Bugs we treat</h2>
<div>{imageCards}</div>
{
lightboxDisplay ?
<div id="lightbox" onClick={hideLightBox}>
<button onClick={showPrev}>?</button>
<img alt="gallery" id="lightbox-img" src={imageToShow}></img>
<button onClick={showNext}>?</button>
</div>
: ""
}
</>
);
}
export default PestsGallery;
uj5u.com熱心網友回復:
您在映射時忘記解構物件的值。你需要改變這個:
const imageCards = images_arr.map((image, text) => (
<img key={image} alt={image} className="image-card" onClick={() => showImage(image)} src={image} />
));
對此:
const imageCards = images_arr.map(({image, text}) => (
<img key={image} alt={image} className="image-card" onClick={() => showImage(image)} src={image} />
));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/405308.html
標籤:
