根据我在react(使用vsc)中为模态设置所遵循的教程,当我使用null时,我不断收到的错误给出了以下信息:
TypeError: setSelectedImage is not a function
handleClick
src/components/modal.js:8
5 | const handleClick = (e) => {
6 | if(e.target.classList.contains('backdrop'))
7 | {
> 8 | setSelectedImage(null);
| ^ 9 | }
10 |
11 |
我的modal.js文件是:
import React from 'react';
const Modal = ({ selectedImage , setSelectedImage}) => {
const handleClick = (e) => {
if(e.target.classList.contains('backdrop'))
{
setSelectedImage(null);
}
};
return (
<div className="backdrop" onClick={handleClick}>
<img src={selectedImage} alt="enlarged pic" />
</div>
)
}
export default Modal;
在使用时:
import GridGallery from "./components/grid-gallery";
import React, {useState} from 'react';
import Modal from './components/modal';
import './components/modal.css';
import "./index.css";
export default function Gallery()
{
const [selectedImage, setSelectedImage] = useState(null);
const images =
[
'../images/SplashPgConc.png',
"../images/Wolf.png",
"../images/SplashPgConc.png",
"../images/Wolf.png",
"../images/SplashPgConc.png",
"../images/Wolf.png",
"../images/SplashPgConc.png",
"../images/Wolf.png",
"../images/SplashPgConc.png",
"../images/Wolf.png",
"../images/SplashPgConc.png",
"../images/Wolf.png"
];
return (
<div className="items-center">
<GridGallery images={images} setSelectedImage={setSelectedImage} />
{selectedImage && <Modal selectedImage={selectedImage} setSelectedImage={setSelectedImage}/> }
</div>
);
}
和网格库,了解更多内容:
import { useState } from "react";
import VisibilitySensor from 'react-visibility-sensor';
export default function GridGallery({images ,setSelectedImage}){
const [imagesShownArray, setImagesShownArray] = useState(
Array(images.length).fill(false)
);
const imageVisibleChange = (index, isVisible) => {
if(isVisible){
setImagesShownArray((currentImagesShownArray) =>{
currentImagesShownArray[index] = true;
return [...currentImagesShownArray];
});
}
};
return(
<div className= "grid grid-cols-3 gap-2">
{images && images.map((imageUrl, index)=> (
<VisibilitySensor
key={index}
partialVisibility={true}
offset={{ bottom: 80 }}
onChange={(isVisible) => imageVisibleChange(index, isVisible)}
>
<GridGalleryCard
imageUrl={imageUrl}
show={imagesShownArray[index]}
setSelectedImage={setSelectedImage}
/>
</VisibilitySensor>
))}
</div>
);
};
function GridGalleryCard({ imageUrl , show , setSelectedImage})
{
return (
<div className={`relative transition ease-in duration-300 transform ${
show ? "" : "translate-y-16 opacity-0"
}`} onClick={() => setSelectedImage(imageUrl)}>
<div className="absolute inset-0 z-10 flex transition duration-200 ease-in hover:opacity-0">
<div className="absolute inset-0 bg-black opacity-70"></div>
<div className="mx-auto text-white z-10 self-center uppercase tracking-widest text-sm">
Hello World
</div>
</div>
<img src ={imageUrl} />
</div>
);
}
我非常困惑为什么要使用 null
和 setSelectedImage
抛出一个错误,有人能澄清这一点和我做错了什么吗?这一切都正常工作,直到我点击图片,然后它抛出错误,而不是关闭模式。我真的为自己能走到这一步感到骄傲。
暂无答案!
目前还没有任何答案,快来回答吧!