【问题标题】:Conditional link styling React条件链接样式 React
【发布时间】:2022-01-04 20:16:07
【问题描述】:

我希望我的导航栏为我所在的页面标题设置样式,例如,我使用 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

标签: javascript css reactjs next.js tailwind-css


【解决方案1】:

使用null 或空字符串"" 代替undefined

同样。使用useState(在这种情况下并不真正需要,但在实践中总是最好使用) https://reactjs.org/docs/hooks-state.html

【讨论】:

  • 它仍然无法正常工作,我开始认为问题不在于语法,而在于条件。
  • 确实,我的路径总是“未定义”,这就是为什么从不匹配 href,如果我解决了它,我还是会发布解决方案
【解决方案2】:

最后问题是路径变量未定义,无法匹配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>
           )
}

【讨论】:

  • 很高兴你解决了这个问题。
  • 感谢您的帮助!
猜你喜欢
  • 2019-09-27
  • 2018-01-03
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
  • 2020-03-14
  • 2020-11-03
  • 2016-03-26
相关资源
最近更新 更多