【问题标题】:How to add HTML attributes (class, etc.) to Blazor components?如何将 HTML 属性(类等)添加到 Blazor 组件?
【发布时间】:2021-03-13 04:55:41
【问题描述】:

这似乎是一个非常基本的问题,但我还没有找到我正在寻找的答案。

假设您有一个名为 <Button> 的 Blazor 组件,该组件具有 Label 等参数。当您使用该组件时,这些参数就像 HTML 属性一样接收:

<Button Label="Sign Up" />

但是如何为组件设置实际的 HTML 属性?!例如,假设您想为组件所代表的元素或标题属性、角色或类型等提供额外的类。以下显然行不通,因为组件标签上的所有属性都是预期的成为该组件的参数:

<Button Label="Sign Up" class="foo" type="submit" id="bar" />

所以,我能想到的唯一方法是为该组件内的每个属性声明一个参数(公共属性)。

<button type="@Type" class="button @Class" id="@Id">@Label</button>

@code {
    [Parameter]
    public string Class { get; set; }

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

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

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

    // And others
}

然后在使用组件时执行以下操作:

<Button Label="Sign Up" Class="foo" Id="bar" Type="Submit" />

但这显然并不理想。这不方便,而且似乎是不必要的抽象层。

所以,我的问题是:这应该怎么做?如果有这样的事情,那么“标准”的做法是什么。难道没有比为每个属性声明参数更方便的方法吗?

我一般是 SPA 框架的新手,所以我也想知道在其他 SPA 框架(例如 React、Angular、Vue 等)中这通常是如何完成的

谢谢。

【问题讨论】:

标签: blazor blazor-server-side blazor-webassembly


【解决方案1】:

你在attribute splatting之后:

<button @attributes="@InputAttributes">@ChildContent</button>

@code {
    [Parameter(CaptureUnmatchedValues = true)]
    public Dictionary<string, object> InputAttributes { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    相关资源
    最近更新 更多