[英]How can I pass the "isActive" prop from NavLink to its children?
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>
);
}
Right now I am using this, using the "isActive" to change a state that is then passed to the child component (to change the icon's background color) but it is giving me a rendering error (despite actually working well).现在我正在使用它,使用“isActive”来更改 state,然后将其传递给子组件(以更改图标的背景颜色),但它给了我一个渲染错误(尽管实际上运行良好)。 Is there a way to pass the "isActive" directly to the child?
有没有办法将“isActive”直接传递给孩子?
In addition to taking a function callback for the className
and style
prop, the NavLink
also takes a render function as the children
prop.除了为
className
和style
属性获取 function 回调之外, NavLink
还将渲染 function 作为children
属性。
Don't use the className
or style
props to issue side-effects like enqueueing state updates.不要使用
className
或style
属性来发出副作用,例如将 state 更新排队。
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); }
Your code:你的代码:
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>
);
}
Dynamically render a className
based on the isActive
property, instead of the style
attribute, and use CSS descendent selectors to change children of the active class.根据
isActive
属性而不是style
属性动态呈现className
,并使用 CSS 后代选择器更改活动 class 的子代。
<NavLink
to={to}
className={({ isActive }) => isActive ? "active" : "" }
>
<Title>{title}</Title>
<SelectedContainerIcon>
<Icon />
</SelectedContainerIcon>
</NavLink>
.active i {
background-color: blue
}
With this solution it probably won't be necessary to save the active
status to state.使用此解决方案,可能不需要将
active
状态保存到 state。 CSS will do the logic for you. CSS 将为您执行逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.