簡體   English   中英

如何使用 tailwind-css 設置 Navlink(react-router-dom) 的活動 state 的樣式?

[英]How can I use tailwind-css to style the active state of the Navlink(react-router-dom)?

我正在嘗試為Navlink的類名使用模板文字,但它不起作用。

這是當前代碼:

className={`px-2 py-2.5 hover:bg-cprimary-300 hover:text-csecond-100 rounded-md transition ${({ isActive }) => isActive ? "bg-red-500" : "bg-black-500"}`}

我嘗試只使用活動部分來檢查是否有其他東西干擾它,但它仍然不起作用。

className={`${({ isActive }) => isActive ? "bg-red-500" : "bg-blue-500"}`}

我使用模板文字的方式有問題嗎?

當我使用它時它有效:

className={({ isActive }) => isActive ? "bg-red-500" : "bg-blue-500"}

試試這個。 className={ px-2 py-2.5 hover:bg-cprimary-300 hover:text-csecond-100 rounded-md transition ${isActive? "bg-red-500": "bg-black-500"} px-2 py-2.5 hover:bg-cprimary-300 hover:text-csecond-100 rounded-md transition ${isActive? "bg-red-500": "bg-black-500"} }

className道具采用字符串function 回調,該回調傳遞isActive道具並返回字符串或未定義。

參見導航鏈接

declare function NavLink( props: NavLinkProps ): React.ReactElement; interface NavLinkProps extends Omit< LinkProps, "className" | "style" | "children" > { caseSensitive?: boolean; children?: | React.ReactNode | ((props: { isActive: boolean }) => React.ReactNode); className?: | string | ((props: { isActive: boolean; }) => string | undefined); // <-- end?: boolean; style?: | React.CSSProperties | ((props: { isActive: boolean; }) => React.CSSProperties); }

使用回調 function 接受isActive屬性並返回一個字符串,其中包含您要應用的 CSS 類。

className={({ isActive }) => [
    "px-2 py-2.5",
    "hover:bg-cprimary-300 hover:text-csecond-100",
    "rounded-md transition",
    isActive ? "bg-red-500" : "bg-black-500"
  ].join(" ")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM