首页 > 解决方案 > 使用 C# 类完全定义的 Razor 组件的 CSS 隔离

问题描述

我有一个名为 的 Razor 组件,RankingCell它完全使用 C# 类定义。没有.razor与之关联的任何文件

// RankingCell.razor.cs
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;

namespace MyProj {
    public class RankingCell: ComponentBase {
        // Some parameters and properties

        [Parameter]
        public string CellElt { get; set; }

        protected override void BuildRenderTree(RenderTreeBuilder builder) {
            /*
             * The thing which prevents me from using a "RankingCell.razor" file to define it.
             * In a .razor file it would be something like this but it is not possible:
             * 
             * <@CellElt ... >@* ... *@</@CellElt>
             * 
             * Please have a look there for for details about how I solved this issue for the component: 
             * https://stackoverflow.com/questions/64196493/in-blazor-how-can-i-dynamically-change-an-html-tag
             */
            builder.OpenElement(0, CellElt);

            // ...

            builder.CloseElement();
        }
    }
}

我想将样式表与我的RankingCell组件相关联,因此我在Microsoft 的有关 CSS 隔离的文档之后创建了这样一个文件,即一个名为的 CSS 文件RankingCell.razor.css

/* RankingCell.razor.css */
.ranking-cell {
    /* RankingCell style */
}

但是当我构建我的项目(使用dotnet build)时,我遇到了以下错误:

RankingCell.razor.css : error BLAZOR102: The scoped css file 'RankingCell.razor.css' was defined but no associated razor component was found for it.

如何解决此 BLAZOR102 问题?如何设法将样式表与我的组件相关联?

该组件看起来没有问题。当没有 CSS 范围文件与之关联并且它在我的 Blazor 项目中工作时,我没有遇到任何编译错误。

我也尝试创建一个空RankingCell.razor文件,但我得到另一个告诉我它BuildRenderTree是在其他地方定义的(当然,因为它已经完全写入RankingCell.razor.cs,组件已完全定义)。

标签: c#asp.net-corerazorblazor

解决方案


您需要像这样向 RankingCell.razor.cs 添加“部分”:

public partial class RankingCell: ComponentBase{
}

推荐阅读