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”直接传递给孩子?
除了为className和styleprop 采用函数回调之外,NavLink还采用渲染函数作为childrenprop。
不要使用className或style属性来发出副作用,例如排队状态更新。
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 | 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>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1943 次 |
| 最近记录: |