使用 CSS 隔离时无法设置 NavLink 的样式

Dav*_*ave 1 blazor blazor-webassembly

我正在尝试为主菜单中的按钮制作一个组件。

<NavLink href="@Href" title="@Title">
    <div class="main-menu-button">
        <img src="@IconUrl" />
        <div class="label">
            @Label
        </div>
    </div>
</NavLink>

@code {

    [Parameter]
    [EditorRequired]
    public string? Href { get; set; }

    [Parameter]
    [EditorRequired]
    public string? Label { get; set; }

    [Parameter]
    public string? Title { get; set; }

    [Parameter]
    [EditorRequired]
    public string? IconUrl { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我似乎无法在 css 文件中定位 NavLink。我已经尝试了所有这些不同的变体,但按钮在激活时永远不会改变颜色。

::deep a.active {
    background-color: red !important;
}

::deep .active {
    background-color: green !important;
}

::deep a .active {
    background-color: blue !important;
}

a.active {
    background-color: yellow !important;
}

a .active {
    background-color: orange !important;
}

Run Code Online (Sandbox Code Playgroud)

当我检查元素时,我可以看到该类active存在。我知道我的 CSS 隔离正在发挥作用,因为我能够添加针对内部元素的样式。

这个问题不仅限于班级active。我也无法将 NavLink 元素定位为text-decoration:none在 css 中设置 ' 。

Jes*_*ood 5

CSS 隔离的工作原理是向组件的所有 html 元素添加自定义范围标识符。结果你写的css

::deep a.active {
    background-color: red !important;
}
Run Code Online (Sandbox Code Playgroud)

变成类似下面的东西

[b-zbwm49ki0i] a.active {
    background-color: red !important;
}
Run Code Online (Sandbox Code Playgroud)

上面的css,意思是select all a elements that have an active class that are inside elements that have a b-zbwm49ki0i attribute. 在您的示例中,不存在将自定义范围标识符作为 的父元素的元素Navlink,因此不应用 css。换句话说,您需要将您的内容包装NavLink在 a 中div才能应用 css。这可确保链接位于具有自定义范围标识符的元素内部。

<div>
    <NavLink href="@Href" title="@Title">
        <div class="main-menu-button">
            <img src="@IconUrl" />
            <div class="label">
                @Label
            </div>
        </div>
    </NavLink>
</div>
Run Code Online (Sandbox Code Playgroud)