我有以下鏈接:
<NavLink to={x.url} className={(x) = x.isActive ? 'active' : 'not-active' } >
<img src={`icon-default.svg`} /> // change from default.svg to active.svg
Link Text
</NavLink>
我的圖示在 HTML 中而不是 CSS 中,我想根據 isActive 呼叫不同的 img,是否可以在子元素(img標簽)上執行此操作?
react-router-dom": "^6.0.2"
謝謝
uj5u.com熱心網友回復:
在react-router-domv6 中, the childrenpropNavLink也接受一個傳遞isActiveprop的函式。該函式必須回傳一個ReactNode(即 JSX)。
導航鏈接 v6
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); end?: boolean; style?: | React.CSSProperties | ((props: { isActive: boolean; }) => React.CSSProperties); }
在childrenprop上使用渲染函式來渲染鏈接內容并有條件地設定影像源屬性。
<NavLink
to={x.url}
className={({ isActive }) = isActive ? 'active' : 'not-active'}
children={({ isActive }) => {
const file = isActive ? "active" : "default";
return (
<>
<img src={`icon-${file}.svg`} />
{x.text}
</>
);
}}
/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/399017.html
上一篇:單擊時反應突出顯示
