如何将“isActive”属性从 NavLink 传递给其子级?

Tur*_*ail 4 javascript jsx reactjs react-router-dom

function NavigationLink({ to, title, exactPath, Icon }) {
  const resolved = useResolvedPath(to);
  const match = useMatch({
    path: resolved.pathname,
    end: exactPath,
  });
  const [active, setActive] = useState(false);

  return (
    <StyledNavLink linkSelected={match}>
      <NavLink
        to={to}
        style={({ isActive }) =>
          isActive ? setActive(true) : setActive(false)
        }
      >
        <Title>{title}</Title>
        <SelectedContainerIcon active={active}>
          <Icon />
        </SelectedContainerIcon>
      </NavLink>
    </StyledNavLink>
  );
}
Run Code Online (Sandbox Code Playgroud)

现在我正在使用它,使用“isActive”来更改状态,然后传递给子组件(以更改图标的背景颜色),但它给了我一个渲染错误(尽管实际上运行良好)。有没有办法将“isActive”直接传递给孩子?

Dre*_*ese 8

除了为classNamestyleprop 采用函数回调之外,NavLink还采用渲染函数作为childrenprop。

不要使用classNamestyle属性来发出副作用,例如排队状态更新。

导航链接

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);
}
Run Code Online (Sandbox Code Playgroud)

你的代码:

function NavigationLink({ to, title, exactPath, Icon }) {
  const resolved = useResolvedPath(to);
  const match = useMatch({
    path: resolved.pathname,
    end: exactPath,
  });

  return (
    <StyledNavLink linkSelected={match}>
      <NavLink to={to}>
        {({ isActive }) => (
          <>
            <Title>{title}</Title>
            <SelectedContainerIcon active={isActive}>
              <Icon />
            </SelectedContainerIcon>
          </>
        )}
      </NavLink>
    </StyledNavLink>
  );
}
Run Code Online (Sandbox Code Playgroud)