在 React 项目中,我创建了菜单,其中包含一些链接,如下图所示,我还更改了链接的背景颜色和活动时文本的颜色,但是,我想更改图标图像,即它会替换活动时的图标图像。那么什么是合适的解决方案?
以下是供您参考的代码:
<List>
{itemList.map((item, index) => {
return (
<ListItem
button
key={item.text}
onClick={() => {
setData(item.text);
}}
>
<NavLink
exact
to={item.link}
style={{ display: "flex", flexWrap: "wrap" }}
activeStyle={{ backgroundColor: "purple", color: "white" }}
>
{item.icon && (
<img
src={item.icon}
style={{ marginRight: "25px" }}
height="18px"
/>
)}
<ListItemText primary={item.text} />
</NavLink>
</ListItem>
);
})}
</List>
我尝试过以下代码:
const [newActiveLink, setNewActiveLink] = useState(false)
<NavLink
exact
to={item.link}
style={{ display: "flex", flexWrap: "wrap" }}
activeStyle={{ backgroundColor: "purple", color: "white" }}
isActive={(match, location) => match ? setNewActiveLink(true) : setNewActiveLink(false)}
>
...
{
newActiveLink == true ? {item.icon && (
<img
src={item.iconWhite}
style={{ marginRight: "25px" }}
height="18px"
/>
)} : {item.icon && (
<img
src={item.icon}
style={{ marginRight: "25px" }}
height="18px"
/>
)}
}
</NavLink>
但是当使用 isActive 时背景颜色消失
找到此代码和框链接:https://codesandbox.io/s/react-material-forked-3uuyg
答案 0 :(得分:0)
我认为你很接近,只需要一些调整。
isActive
应该返回一个布尔值,如果当前链接应该是活动的,useState
状态更新器函数是空返回。代码:
const [newActiveLink, setNewActiveLink] = useState(null);
...
<NavLink
exact
to={item.link}
style={{ display: "flex", flexWrap: "wrap" }}
activeStyle={{ backgroundColor: "purple", color: "white" }}
isActive={(match, location) => {
match && setNewActiveLink(index); // <-- set active index
return match; // <-- return boolean
}}
>
{newActiveLink === index // <-- check active index against current index
? item.iconWhite && (
<img
src={item.iconWhite}
style={{ marginRight: "25px" }}
height="18px"
/>
)
: item.icon && (
<img
src={item.icon}
style={{ marginRight: "25px" }}
height="18px"
/>
)}
<ListItemText primary={item.text} />
</NavLink>