有没有办法在不覆盖现有 class 名称的情况下将 class 名称添加到 Blazor 组件?

Is there a way to add a class name to a blazor component without overriding the existing class name?

假设我有一个组件 MyComponent,声明如下:

<div class="container">
  "some nested content"
</div>

现在我想使用组件,并给它一个 class 名称:

<MyComponent class="new-class" />

如果我这样做,“容器”class 名称将被“new-class”覆盖:

<div class="new-class">
  ....
<div>

有没有办法保留两个 class 的名字并在最后有:

<div class="container new-class">
  ....
<div>

您应该了解“组件参数”:[Parameter]。在您的组件上,声明一个参数:

<div class="container @CssClass">
  "some nested content"
</div>

@code
{
   [Parameter] public string CssClass {get; set;} = "";
}

现在,当您使用组件时,如果需要,您可以为参数设置一个值:

<MyComponent CssClass="new-class" />

引用 docs:

Components can have component parameters, which are defined using public simple or complex properties on the component class with the [Parameter] attribute. Use attributes to specify arguments for a component in markup.