【问题标题】:how to change material Icons Styles used in navLink when link is active?当链接处于活动状态时,如何更改 navLink 中使用的材质图标样式?
【发布时间】:2020-12-13 20:16:14
【问题描述】:

这是我的代码:

import React from "react";
import "./sidebar.scss";
import HomeOutlinedIcon from "@material-ui/icons/HomeOutlined";
import InfoOutlinedIcon from "@material-ui/icons/InfoOutlined";
import ChatOutlinedIcon from "@material-ui/icons/ChatOutlined";
import LanguageIcon from "@material-ui/icons/Language";
import { NavLink } from "react-router-dom";


<div className="sidebar__Wrapper">
    <div className="iconsContainer">
        <div className="icons">
        <NavLink to="/">
            <HomeOutlinedIcon className="iconsDefaultStyle" />
        </NavLink>
        <NavLink to="/worldwide">
            <LanguageIcon className="iconsDefaultStyle" />
        </NavLink>
        <NavLink to="/importantinfo">
            <InfoOutlinedIcon
            className="iconsDefaultStyle"
            fontSize="default"
            />
        </NavLink>
        </div>
    </div>
</div>

我在NavLink 中使用 Material UI 图标,最初图标的颜色是灰色,但我想在链接处于活动状态时更改图标的颜色,我的意思是我想要做的是:

当我单击图标时,必须更改图标的颜色,这将表明当前链接处于活动状态。我通过为每个链接使用单独的状态来做到这一点,当单击特定图标时,这将更改类,但这会使我的代码非常冗长。有没有其他方法可以做到这一点?

【问题讨论】:

  • 你能分享你正在使用的导入吗?
  • 您可以保持“activeLink”状态,该状态会根据所选链接而变化。然后,您可以使用三元组来决定显示哪个类:className="{activeLink === "home" ? "yourActiveClass" : "iconsDefaultStyle"。
  • @KennyJohnJacob 我编辑了帖子现在你可以看到 Imports
  • @Phobos 我明白你在说什么,但为此我需要创建超过 1 个状态,我的意思是我需要为每个图标(链接)单独设置状态。

标签: javascript reactjs react-router frontend


【解决方案1】:

您可以修改您的代码以具有这种格式

import { Link, useLocation } from "react-router-dom";
import MenuItem from '@material-ui/core/MenuItem';

const { pathname } = useLocation();

<MenuItem className={pathname === "/worldwide" ? "active": "inactive"} 
  component={Link} to="/worldwide">
    <LanguageIcon className="iconsDefaultStyle" />
</MenuItem>

这个想法是你从反应路由器获取当前路径名,并且对于每个链接,你将编写一个条件,如果路径名匹配该路由,则该条件变为真。 (见原文https://stackoverflow.com/a/50614553/8323067

这里可以根据相同的条件将className设置为css类(as mentioned by @Phobos

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-03
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    相关资源
    最近更新 更多