条件 link 样式 React

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(在这种情况下并不真正需要,但在实践中总是最好使用) https://reactjs.org/docs/hooks-state.html

最后问题是路径变量未定义,无法匹配 href,因此条件未满足。

解决方案:使用参数 .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>
           )
}