![](/img/trans.png)
[英]How do I pass a prop from a Parent styled component to its children's styled components no matter how deep
[英]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>
);
}
現在我正在使用它,使用“isActive”來更改 state,然后將其傳遞給子組件(以更改圖標的背景顏色),但它給了我一個渲染錯誤(盡管實際上運行良好)。 有沒有辦法將“isActive”直接傳遞給孩子?
除了為className
和style
屬性獲取 function 回調之外, NavLink
還將渲染 function 作為children
屬性。
不要使用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); }
你的代碼:
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>
);
}
根據isActive
屬性而不是style
屬性動態呈現className
,並使用 CSS 后代選擇器更改活動 class 的子代。
<NavLink
to={to}
className={({ isActive }) => isActive ? "active" : "" }
>
<Title>{title}</Title>
<SelectedContainerIcon>
<Icon />
</SelectedContainerIcon>
</NavLink>
.active i {
background-color: blue
}
使用此解決方案,可能不需要將active
狀態保存到 state。 CSS 將為您執行邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.