我想向 MudButton 添加更多逻辑,以在单击按钮时扩展加载状态
我完成了这个实现,但我认为这不是最佳实践。
我希望能从您那里得到任何改进。谢谢!
P/s:我从这个链接获取MudButton的内容https://github.com/MudBlazor/MudBlazor/blob/dev/src/MudBlazor/Components/Button/MudButton.razor
// MudButtonLoading.razor
@inherits MudButton
<MudElement @bind-Ref="@_elementReference"
HtmlTag="@HtmlTag"
Class="@Classname"
Style="@Style"
@attributes="UserAttributes"
@onclick="OnClickHandler"
type="@ButtonType.ToDescriptionString()"
href="@Href"
target="@Target"
rel="@GetRel()"
disabled="@disabledState"
ClickPropagation="@ClickPropagation">
<span class="mud-button-label">
@if (!string.IsNullOrWhiteSpace(StartIcon))
{
<span class="@StartIconClass">
@if (!isProcessing)
{
<MudIcon Icon="@StartIcon" Size="@(IconSize ?? Size)" Color="@IconColor" />
}
else
{
<MudProgressCircular Class="ms-n1" Size="LoadingSize" Indeterminate="true" />
}
</span>
}
@if (isProcessing)
{
@if (string.IsNullOrWhiteSpace(StartIcon) && string.IsNullOrWhiteSpace(EndIcon))
{
<MudProgressCircular Class="ms-n1" Size="LoadingSize" Indeterminate="true" />
}
}
@ChildContent
@if (!string.IsNullOrWhiteSpace(EndIcon))
{
<span class="@EndIconClass">
@if (!isProcessing)
{
<MudIcon Icon="@EndIcon" Size="@(IconSize ?? Size)" Color="@IconColor" />
}
else
{
<MudProgressCircular Class="ms-n1" Size="LoadingSize" Indeterminate="true" />
}
</span>
}
</span>
</MudElement>
// MudButtonLoading.razor.cs
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.AspNetCore.Components.Web;
using MudBlazor;
namespace Sample.Client.Components.Buttons
{
public partial class MudButtonLoading
{
protected bool isProcessing;
protected bool disabledState => base.GetDisabledState() || isProcessing;
protected override async Task OnClickHandler(MouseEventArgs ev)
{
try
{
isProcessing = true;
//StateHasChanged();
//await Task.Delay(1);
await base.OnClickHandler(ev);
}
finally
{
isProcessing = false;
}
}
protected Size LoadingSize => IconSize ?? Size switch
{
Size.Small => Size.Small,
var other => other - 1
};
}
}
我已经这样做了..我确信有更好的方法(即,在加载更改时不要“重新绘制”整个按钮。我在 razor/blazor 学习周期的早期就做了这个,但它有效。 .) :)
@inherits MudButton
@if (Loading) {
<MudButton Disabled="true" Variant="@base.Variant" Class="@base.Class" Color="@base.Color">
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
<MudText Class="ms-2">Processing</MudText>
</MudButton>
} else {
@RenderBase();
}
@code {
[Parameter] public bool Loading { get; set; }
RenderFragment RenderBase() => builder => base.BuildRenderTree(builder);
protected override void OnInitialized()
{
//base.Color = Color.Primary;
base.Variant = Variant.Filled;
base.OnInitialized();
}
}