条件链接样式 React

Posted

技术标签:

【中文标题】条件链接样式 React【英文标题】:Conditional link styling 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 【参考方案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>
           )

【讨论】:

很高兴你解决了这个问题。 感谢您的帮助!

以上是关于条件链接样式 React的主要内容,如果未能解决你的问题,请参考以下文章

如何在 react-router v4 中设置活动链接的样式?

带有样式组件的样式链接

React&Material UI-如何根据路线删除导航按钮/链接?

navitem 中的 React-Bootstrap 链接项

在 React Native 中链接 CSS 框架

React.js Material-UI 中的底部导航样式