我正在尝试定义一个充当引导警报包装器的组件。
BootstrapAlert.razor
<div class="alert alert-@AlertType d-@(string.IsNullOrEmpty(Message) ? "none" : "block")" role="alert">
@Message
</div>
@code {
[ParameterAttribute]
private string AlertType { get; set; } = "info"; // Default alert type
[ParameterAttribute]
private string? Message { get; set; }
// Method to update the alert type and message
public async Task ShowAsync(string alertType, string message)
{
AlertType = alertType;
Message = message;
await InvokeAsync(StateHasChanged);
}
// Method to hide the alert
public async Task HideAsync()
{
Message = null;
await InvokeAsync(StateHasChanged);
}
protected override async Task OnParametersSetAsync()
{
//Message is ALWAYS null here
await base.OnParametersSetAsync();
}
}
页:
<form class="row" @onsubmit="SubmitForm" @onsubmit:preventDefault>
<Alert @ref=SaveAlert></Alert>
<button type="submit">Save</button>
</form>
@code {
private Alert? SaveAlert;
private async Task SubmitForm()
{
try
{
await SetIsLoading(true); //DISPLAYS A LOADING SPINNER
if (SaveAlert != null) await SaveAlert.HideAsync();
//.......
if (SaveAlert != null) await SaveAlert.ShowAsync("success", "OK");
}
catch (Exception ex)
{
if (SaveAlert != null) await SaveAlert.ShowAsync("danger", ex.Message);
}
finally
{
await SetIsLoading(false);
}
StateHasChanged();
}
}
警报组件从未更新,在“OnParametersSetAsync”中“Message”参数始终为空。
我尝试过非异步版本的方法,到处都放“StateHasChanged”,不调用“Hide”方法,还删除了[ParameterAttribute]属性,因此它被用作常规变量,但对我来说似乎没有什么用
我对 Blazor 还不太熟悉,所以不知道还有什么相关内容。我使用的应用程序为 RenderMode="Server"
我做错了什么?