如何为使用Expo Router的Web项目样式化活跃链接?
在Expo Router Web项目中给活跃导航链接加样式
Expo Router没有内置类似React Router的NavLink组件,但可以通过usePathname钩子手动实现活跃链接的样式控制,具体步骤如下:
1. 导入依赖
从expo-router里导入需要的Link组件和usePathname钩子:
import { Link, usePathname } from 'expo-router';
2. 获取当前页面路径
在你的导航组件内部,调用usePathname拿到当前的路由路径:
const pathname = usePathname();
3. 给链接加条件样式
通过判断当前路径是否和链接的href匹配,为活跃链接应用特殊样式,这里提供两种常用方式:
方式一:内联样式
直接在Link组件的style属性里写判断逻辑:
<Link href="/home" style={{ color: pathname === '/home' ? '#165DFF' : '#333', fontWeight: pathname === '/home' ? 'bold' : 'normal', borderBottom: pathname === '/home' ? '2px solid #165DFF' : 'none' }} > Home </Link> <Link href="/about" style={{ color: pathname === '/about' ? '#165DFF' : '#333', fontWeight: pathname === '/about' ? 'bold' : 'normal', borderBottom: pathname === '/about' ? '2px solid #165DFF' : 'none' }} > About </Link> <Link href="/product" style={{ color: pathname === '/product' ? '#165DFF' : '#333', fontWeight: pathname === '/product' ? 'bold' : 'normal', borderBottom: pathname === '/product' ? '2px solid #165DFF' : 'none' }} > Product </Link>
方式二:使用CSS类名(更便于维护)
先定义CSS类:
.nav-link { color: #333; font-weight: normal; border-bottom: none; padding: 8px 16px; transition: all 0.2s ease; } .nav-link.active { color: #165DFF; font-weight: bold; border-bottom: 2px solid #165DFF; }
然后在组件里写个小函数来判断并返回对应的类名:
// 封装判断逻辑,避免重复代码 const getNavLinkClass = (href) => { return pathname === href ? 'nav-link active' : 'nav-link'; }; return ( <div className="nav-container"> <Link href="/home" className={getNavLinkClass('/home')}>Home</Link> <Link href="/about" className={getNavLinkClass('/about')}>About</Link> <Link href="/product" className={getNavLinkClass('/product')}>Product</Link> </div> );
4. 匹配子路径(可选)
如果需要把/product/123这类子路径也视为/product链接处于活跃状态,可以修改判断逻辑为:
const getNavLinkClass = (href) => { return pathname.startsWith(href) ? 'nav-link active' : 'nav-link'; };
内容的提问来源于stack exchange,提问作者manas
相关产品推荐
相关产品推荐

