react-scroll点击无响应,提示'target Element not found'问题求助
解决方案
核心问题
你遇到的target Element not found错误,根源是react-scroll的Link组件to属性格式错误。react-scroll依赖页面内元素的id实现滚动定位,不需要添加/或#前缀,你当前把to写成了路由路径格式(比如/#Home),导致组件无法找到对应id的目标元素。
修复步骤
- 调整导航数组格式:移除
navigation数组中的#前缀,直接存储目标元素的id名称 - 修正
Link的to属性:直接使用id字符串,无需额外路径前缀 - 同步激活状态判断:导航数组不再带
#,状态判断逻辑也要对应更新 - 验证页面元素id:确保页面内存在对应id的容器(比如
<section id="Home">)
修正后的代码
import React, { useState } from 'react' import cn from 'classnames' import { Link } from "react-scroll" import Logo from '../Logo/Logo' import styles from './Layout.module.scss' interface ILayoutProps { children: React.ReactNode } export default function Layout({ children }: ILayoutProps) { const [activeTab, setActiveTab] = useState('Home') // 移除#前缀,直接存储目标元素id const navigation = ['Home', 'About', 'Portfolio', 'Contact'] console.log(activeTab); return ( <div> <nav className={styles.navContainer}> {/* to直接传入目标id */} <Link to='Home' spy={true} smooth={true} offset={50} duration={500}> <Logo /> </Link> <ul className={styles.navItems}> {navigation.map((nav, index) => { return ( <li key={index}> <Link {/* 直接使用id作为to的值 */} to={nav} className={cn(styles.linkItem, { [styles.activeTab]: activeTab === nav })} onClick={() => { setActiveTab(nav) console.log(nav) }} spy={true} smooth={true} offset={50} duration={500} > {nav} </Link> </li> ) })} </ul> <a className={styles.button} href='assets/Stas_Gavrilov_resume.txt' download>Resume</a> </nav> <main>{children}</main> </div> ) }
额外注意事项
- 确认页面内容区域的id与导航项完全匹配,例如:
<section id="Home">首页内容</section> <section id="About">关于内容</section> - 如果滚动后内容被固定导航栏遮挡,可以调整
offset值(比如设置为导航栏的高度)来修正定位
内容的提问来源于stack exchange,提问作者Stas Gavrilov
相关产品推荐
相关产品推荐

