键入Blazor组件的安全字符串参数



我对Blazor和C#都是新手,但我在看Blazorise UI包时注意到,当你想提供一个";颜色";属性设置为按钮,它将强制您使用类似Color="彩色原色";或Color=";颜色。警告";。如何在我自己的剃须刀组件中实现这一点?

使用剃须刀的随机组件按钮组件

<Button @onclick="TestClick2" Color="BtnColor.Danger">Test 3</Button> <--- Color parameter is not working here. It just uses the literal string of 'BtnColor.Danger' instead of 'danger'

按钮剃刀

<button class="btn @_btnColorClass">
@ChildContent
</button>

Button.razar.cs

using Microsoft.AspNetCore.Components;
using System.Collections.Generic;
namespace BlazorServer.UI.Buttons
{
public partial class Button : ComponentBase
{
private string _btnColorClass;
public static class BtnColor
{
public const string Primary = "primary";
public const string Secondary = "secondary";
public const string Danger = "danger";
}
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter(CaptureUnmatchedValues = true)]
public Dictionary<string, object> AdditionalAttributes { get; set; }
[Parameter]
public string Color { get; set; } = BtnColor.Primary;   <------- here?!?
protected override void OnInitialized()
{
_btnColorClass = $"btn-{ Color }";
}
}
}

如果您想将参数保持为字符串(这意味着您可以使用预定义的条目或自己编写(,那么请使用常量。

public static class BtnColor
{
public const string Primary = "Primary";
// ...
}

您也可以更改参数以使用枚举而不是字符串。

[Parameter]
public BtnColor Color { get; set; } = BtnColor.Primary;
public enum BtnColor
{
Primary,
// ...
}
css classes:
.primary{}
.secondary{}
.danger{}

color enum:
public enum Color{ Primary, Secondary, Danger}
Parameter:
[Parameter]
public Color Color { get; set; } = Color.Primary;
html:
<button class="@Color.ToString().ToLower()">@childcontent</button>
public enum Color
{
Primary,
Secondary,
Danger
}
public static class ColorExtensions
{
public static string GetString(this Color me)
{
switch (me)
{
case Color.Primary:
return "Primary";
case Color.Secondary:
return "Secondary";
case Color.Danger:
return "Danger";
default:
return "";
}
}
}

用法:

Color color = Color.Primary;
string output = color.GetString();

最新更新