首页 > 解决方案 > 设置 className 并使用 styledComponents 创建一个动作

问题描述

为什么这不起作用?我想在我的 NavigationBar 中给这个 NavigationTab 一个不同的背景颜色。稍后当我选择它时,活动选项卡应显示为红色背景。就像我们知道不同的导航菜单一样。

<NavigationLinkContainer className={"active"} onClick={() => { window.location.href = "/" }}>
const NavigationLinkContainer = styled.div`
    display: flex;
    flex-flow: row;
    align-items: center;
    box-sizing: border-box;
    transition: 0.3s ease-in-out;
    margin: 0px;
    cursor: pointer;
    height: 50px;


    .active {
        background-color: #D1495B; 

    }

    /* &:hover {
        background-color: ${colors.softRed};
    } */
    &:hover {
        color: ${colors.white};
        background: ${colors.softRed};


        &:before {
            height: 100%;
            transition: 0.3s ease-in-out;
        }
    }


    @media (max-width: 1000) {
        padding: 15px;
        border-bottom: 4px solid transparent;

        &:hover {
            background-color: azure;
        }

        &:active, &:hover {
            color: azure;
            border-bottom: 4px solid azure;
        }

        &:before {
            display: none;
        }
    }


`

标签: htmlcssreactjsstyled-components

解决方案


您没有为活动类使用正确的选择器。添加父选择器&以在组件具有active类时应用样式。

const NavigationLinkContainer = styled.div`
    display: flex;
    flex-flow: row;
    align-items: center;
    box-sizing: border-box;
    transition: 0.3s ease-in-out;
    margin: 0px;
    cursor: pointer;
    height: 50px;

    // use the parent selector &
    &.active {
        background-color: #D1495B; 
    }

   .
   .
   .
   . 

`

希望这可以帮助!


推荐阅读