[英]Conditional link styling React
我希望我的導航欄設置我所在的頁面標題的樣式,我使用 React 和 Tailwind CSS,例如,當我在所選路徑上時,只需將標題設為黃色。
我實現這一目標的邏輯是這樣但不起作用:
<div className={active ? "text-yellow-400" : undefined}
我的潰敗代碼:
const LinkItem = ({href, path, children, ...props}) => {
const active = path === href
return (
<NextLink href={href}>
<div className={active ? "text-yellow-400" : undefined}
{...props}
>
{children}
</div>
</NextLink>
)
}
導航條碼:
const Navbar = props => {
const {path} = props
return (
<LinkItem href="/page1" path={path}>
Page 1
</LinkItem>
)
}
而不是undefined
使用null
或空字符串""
同樣。 使用useState
(在這種情況下並不真正需要,但在實踐中使用它總是最好的)
最后問題是路徑變量未定義,並且無法匹配href,因此條件從未滿足。
解決方案:使用 parameter.asPath 從 useRouter 掛鈎調用路徑,這將返回我存儲在路徑變量中的參數。
代碼:
import NextLink from 'next/link'
import {useRouter} from "next/router";
const LinkItem = ({href, children, ...props}) => {
const path = useRouter().asPath
const active = path === href
return (
<NextLink href={href}>
<div className={active ? "<styles here>" : "<styles here>"}
{...props}
>
{children}
</div>
</NextLink>
)
}
導航條碼:
const Navbar = props => {
const {path} = props
return (
<LinkItem href="/page1" path={path}>
Page 1
</LinkItem>
<LinkItem href="/page2" path={path}>
Page 2
</LinkItem>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.