React项目特定JSX代码段事件与Router功能失效问题
React项目中特定JSX代码段内事件与Router功能失效
问题现象
在React项目里,特定JSX代码段内的Link组件和自定义点击事件均无法正常工作:
- DOM已渲染出
a元素,但点击后URL无变化,控制台无报错或任何输出 - 仅
frame-container直接子元素位置的Link能正常跳转,frame内部所有位置的Link完全失效
初始代码(PhotoFrame.tsx)
const PhotoFrame = ({ photoId }: PhotoFrameProps) => { const photo = useAppSelector((state: RootState) => selectPhotoById(state, photoId) ); const navigate = useNavigate(); const url = photo.urls.regular; const author = photo.user.name; const authorUsername = photo.user.username; const path = `/user/${authorUsername}`; const authorPhotoUrl = photo.user.profile_image.small; return ( <article className="frame-container" > {/* <Link to={path}>{author}</Link> */} ----> 此处Link可正常工作 <div className="frame"> {/* <Link to={path}>{author}</Link> */} ----> 此处Link无法工作 <img src={url} alt={`Photography by ${author}`} /> <address className="author"> <img src={authorPhotoUrl} alt="Author" /> <Link to={path}>{author}</Link> ----> 此处Link无法工作(原位置) </address> </div> {/* <Link to={path}>{author}</Link> */} ----> 此处Link无法工作 </article> ); };
进一步排查尝试
我原本以为只是Router的Link组件异常,于是给address元素添加onClick事件,通过useNavigate钩子实现跳转,但发现事件完全未触发——控制台连CLICK日志都无法输出。后续尝试将address替换为button等其他元素,问题依然存在。
添加事件后的代码:
const handleAddressClick: MouseEventHandler<HTMLElement> = (e) => { e.stopPropagation(); console.log("CLICK"); ---> 控制台无输出 navigate(path); }; return ( <article className="frame-container" > <div className="frame"> <img src={url} alt={`Photography by ${author}`} /> <address className="author" onClick={handleAddressClick}> <img src={authorPhotoUrl} alt="Author" /> </address> </div> </article> );
内容的提问来源于stack exchange,提问作者N.N.
相关产品推荐
相关产品推荐

