Sex*_*yMF 4 reactjs react-router react-router-dom
我有以下链接:
<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>
Run Code Online (Sandbox Code Playgroud)
img我的图标位于 HTML 而不是 CSS 中,我想根据 isActive 调用不同的 img,是否可以在子元素(标签)上执行此操作?
react-router-dom": "^6.0.2"
谢谢
在react-router-domv6中children, the 的 propNavLink也接受一个传递isActiveprop 的函数。该函数必须返回一个ReactNode(即 JSX)。
Run Code Online (Sandbox Code Playgroud)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); }
在 prop上使用渲染函数children来渲染链接内容并有条件地设置图像源属性。
<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}
</>
);
}}
/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2313 次 |
| 最近记录: |