简体   繁体   English

从 React 地图功能保存图像

[英]save image from React map function

I want to transfer an image from one useState function to another when clicked我想在单击时将图像从一个 useState 函数传输到另一个函数

const [images, setImages] = useState([]);
  useEffect(() => {
    setImages(ImgArray);
  }, []);

this is where I get my source image from which is这是我从中获取源图像的​​地方

export const ImgArray = [
    {
        id: 1,
        src: 'https://cdn.britannica.com/s:600x1000/91/181391-050-1DA18304/cat-toes-paw-number-paws-tiger-tabby.jpg'
        
    }
];

my idea was to, whenever i click on an image that exact image in the array is going to be saved into my 'setLightboxImage'我的想法是,每当我单击图像时,数组中的确切图像将被保存到我的“setLightboxImage”中

const [lightboxImage, setLightboxImage] = useState([]);

<div className="header">

{images.map((image)=>(<React.Fragment><img alt="" src={image.src} key={image.id} onClick={setLightboxImage(image.src)} /> <div></div></React.Fragment>))}

    </div>

but i guess it doesn't work that way... can i somehow handle this in another way perhaps in a seperate function?但我想它不能那样工作......我能不能以另一种方式处理这个问题,也许是在一个单独的函数中?

Also as a sidenote everything is wrapped inside of an Arrow function component ' const App = () => {return(...)} '另外作为旁注,所有内容都包含在 Arrow 函数组件“ const App = () => {return(...)} ”中

By calling the function with the brackets "()", the function will be triggered at initialization.通过调用带括号“()”的函数,函数将在初始化时触发。

You could use this way:你可以这样使用:

const [lightboxImage, setLightboxImage] = useState([]);

<div className="header">

{images.map((image)=>
(<React.Fragment>
<img alt="" 
src={image.src} 
key={image.id} 
onClick={() => {setLightboxImage(image.src)}} /> 

<div></div>
</React.Fragment>))}
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM