React NavLink根据isActive改变子元素

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"

谢谢

Dre*_*ese 6

react-router-domv6中children, the 的 propNavLink也接受一个传递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);
}
Run Code Online (Sandbox Code Playgroud)

在 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)