Javascript React影像玻璃放大镜

问题描述

我有这个玻璃放大镜(来自https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_image_magnifier_glass),在我的react项目中可以正常打开onClick,但是我想让它在其他点击时切换打开/关闭状态,但是没有关闭。

这是我应该实现的功能,但是无论我的zoomActive状态设置为true还是false,缩放始终保持打开状态。谁能告诉我我在做什么错?谢谢!

 const [zoomActive,setZoomActive] = useState(false)

    /* Initiate Magnify Function
with the id of the image,and the strength of the magnifier glass:*/
    const handleMagnifier = () => {
        setZoomActive(!zoomActive)
        zoomActive && magnify(myImageId,3)
        console.log('MAGNIFIER-GLASS-STATE???',zoomActive)
    }

这里是onClick函数:

 <div
                                    className="img-magnifier-container"
                                    onClick={handleMagnifier}
                                >
                                    <img
                                        id={myImageId}
                      
                                        src={graphicImage}
                                        alt="mobile graphic"
                                    />
                                </div>

和CSS:

.img-magnifier-container {
    position: relative;
    cursor: zoom-in;
}
.img-magnifier-glass {
    position: absolute;
    border: 3px solid $tangerine;
    border-radius: 50%;
    cursor: none;
    /*Set the size of the magnifier glass:*/
    width: 200px;
    height: 200px;
}

解决方法

以防万一,它对我有帮助。像这样:

 const handleMagnifier = () => {
        setZoomActive(!zoomActive)
        let glass = document.getElementsByClassName('img-magnifier-glass')
        !zoomActive ? magnify(myImageId,3) : glass[0].removeAttribute('class')
    }

不确定这是否是最好的方法,但是它可行。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...