我正在尝试构建一个动态应用程序。当您单击图片时,它应该会更改为另一张图片。因此,我将 src 路径存储在一个名为 arrays 的数组中。然后,对于图像,我尝试使用数组“arrays”的名称和我想要的路径的位置,而不是对图像路径进行硬编码。但是两张图片都无法加载,我不明白为什么。 我已经尝试使用 require 但它也不起作用。也许有人知道为什么它不起作用? 谢谢。
我还要求聊天 gpt 给我编写一个如何动态输出图像的示例,它的代码如下:
> import React,{useState} from 'react';
> import './Secondphoto.css';
> //import ImageArray from './ImageArray.js';
>
> const Secondphoto = (props) => {
> const arrays = ["../images/mantelfrau.jpg", "../images/whitewoman.jpg", "../images/arraypicthree.jpg", "../images/arraypicfour.jpg", "../images/arraypicfive.jpg","../images/arraypicsix.jpg"]
> const [clicked, setClicked] = useState(false);
> console.log(clicked);
> const selectedImageIndex = 1;
> const selectedImageURL = arrays[selectedImageIndex];
> return(
> <div className="flex_container_secondphoto">
> <img src={selectedImageURL} alt="woman wearing something white" className="secondphoto" onClick= {() => setClicked(true)}/>
> </div>
> )
> }
>
> export default Secondphoto;
但是也没有用。
要完成这项工作,您需要做一些改变。 首先,你的
SecondPhoto
应该看起来像这样:
function SecondPhoto({image, onImageClicked}){
return(
<div className="flex_container_secondphoto">
<img src={require(`../${image}`)} alt="woman wearing something white" className="secondphoto" onClick={onImageClicked}/>
</div>
)
}
export default SecondPhoto;
包含图像的组件将看起来:
const arrays = ["images/mantelfrau.jpg", "images/whitewoman.jpg"...];
const [index, setIndex] = useState(0);
const onImageClicked = () => {
setIndex(index === arrays.length - 1 ? 0 : index + 1);
}
return(
<div className="flex_container_secondphoto">
<SecondPhoto image={arrays[index]} onImageClicked={onImageClicked} />
</div>
)
}
对图像数组和索引使用 Usestate
import React, { useState } from "react";
import "./Secondphoto.css";
const Secondphoto = (props) => {
const [imageArray, setImageArray] = useState([
"../images/mantelfrau.jpg",
"../images/whitewoman.jpg",
"../images/arraypicthree.jpg",
"../images/arraypicfour.jpg",
"../images/arraypicfive.jpg",
"../images/arraypicsix.jpg",
]);
const [selectedImageIndex, setSelectedImageIndex] = useState(0);
return (
<div className="flex_container_secondphoto">
<img
src={imageArray[selectedImageIndex]}
alt="woman wearing something white"
className="secondphoto"
onClick={() =>
setSelectedImageIndex(
(selectedImageIndex + 1) % imageArray.length
)
}
/>
</div>
);
};
export default Secondphoto;
这里
(selectedImageIndex + 1) % imageArray.length
循环遍历数组中的所有图像