React构建图片地图时显示坐标函数报错及clientHeight空值问题
解决React图片地图组件的两个报错问题
1. 修复Unexpected use of 'event' no-restricted-globals错误
你最初的onClick={showCoords(event)}写法存在两个问题:
- 直接执行了
showCoords函数,而非传递函数引用给onClick,这会导致组件一渲染就触发弹窗,而非点击图片时触发 - 这里的
event是全局变量,ESLint规则no-restricted-globals禁止直接使用全局event
解决方法:
直接将函数引用传给onClick即可,React会自动把点击事件对象作为参数传入回调:
<img src={solarSystem} alt="Solar System" usemap="#SSMap" id="SS" onClick={showCoords} />
如果需要额外参数,再用箭头函数包裹:
<img src={solarSystem} alt="Solar System" usemap="#SSMap" id="SS" onClick={(e) => showCoords(e, extraParam)} />
2. 修复Cannot read properties of null (reading 'clientHeight')错误
报错原因是组件渲染阶段,<img>还未挂载到DOM树上,此时调用document.getElementById("SS")会返回null,自然无法读取clientHeight。
推荐方案:使用React的useRef钩子(符合React范式)
- 引入
useRef和useEffect钩子 - 创建ref绑定到图片元素
- 在
useEffect中(组件挂载完成后)获取图片高度
完整代码示例:
import { useRef, useEffect } from 'react'; function SS() { const imgRef = useRef(null); useEffect(() => { // 组件挂载完成后,imgRef.current指向DOM元素 if (imgRef.current) { console.log(imgRef.current.clientHeight); } }, []); // 空依赖数组确保只在挂载后执行一次 function showCoords(event) { alert(event.pageX + " " + event.pageY); } return( <div> <img ref={imgRef} src={solarSystem} alt="Solar System" usemap="#SSMap" id="SS" onClick={showCoords} /> {/* 补充你的map元素,比如<map name="SSMap">...</map> */} </div> ); }
备选方案:使用useEffect配合getElementById
如果坚持用getElementById,同样要把获取高度的代码放到useEffect里:
import { useEffect } from 'react'; function SS() { useEffect(() => { const img = document.getElementById("SS"); if (img) { console.log(img.clientHeight); } }, []); // 其余代码不变 }
额外说明:如果图片是远程加载的,clientHeight可能在图片加载完成前为0,此时需要监听图片的load事件:
useEffect(() => { const handleLoad = () => { console.log(imgRef.current.clientHeight); }; if (imgRef.current) { imgRef.current.addEventListener('load', handleLoad); // 组件卸载时移除监听 return () => imgRef.current.removeEventListener('load', handleLoad); } }, []);
内容的提问来源于stack exchange,提问作者DennisM
相关产品推荐
相关产品推荐

