【问题标题】:CSS isolation for a Razor component which is fully defined with a C# class使用 C# 类完全定义的 Razor 组件的 CSS 隔离
【发布时间】:2021-03-29 01:10:55
【问题描述】:

我有一个名为RankingCell 的 Razor 组件,它完全使用 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's documentation about CSS isolation 之后创建了这样一个文件,即一个名为RankingCell.razor.css 的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-core razor blazor


【解决方案1】:

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

public partial class RankingCell: ComponentBase{
}

【讨论】:

  • 如果你说这是如何为同一个组件拥有一个 .razor 文件和一个 .cs 文件会更清楚,否则它可以被视为单独解决范围 CSS 问题的解决方案。
猜你喜欢
  • 2021-04-07
  • 2021-05-01
  • 2017-06-06
  • 2022-07-15
  • 2021-07-08
  • 2021-02-20
  • 1970-01-01
  • 2015-04-01
  • 2021-03-26
相关资源
最近更新 更多