当我第一次单击按钮时,通知组件已渲染,但当我再次单击按钮时,该组件未渲染,为什么?
我应该为重新渲染通知组件做什么?
//home.cs
//some code with html
需要使用绑定来实现显示/隐藏。 我重构了你的代码来演示如何重构。
Notification
。 我已经:
onclicked
修复为 @onclicked
。EventCallback
以实现ShowAlert
上的双向绑定。CloseAlert
以调用EventCallback。bi-x-circle
是什么。@if (this.ShowAlert)
{
<div class="container-fluid">
<div class="row">
<div class="=col-sm-12 col-sm-12 col-md-6 col-lg-4 col-xl-4">
<div class="alert @AlertClass mt-2 p-0" role="alert">
<button type="button" class="btn" @onclick="CloseAlert">
<span>X</span>
</button>
@this.AlertMessage
</div>
</div>
</div>
</div>
}
@code {
[Parameter] public bool ShowAlert { get; set; } = false;
[Parameter] public EventCallback<bool> ShowAlertChanged { get; set; }
[Parameter] public string AlertClass { get; set; } = "alert-info";
[Parameter] public string? AlertMessage { get; set; }
private void CloseAlert()
{
this.ShowAlertChanged.InvokeAsync(false);
}
}
还有
Home
,我对其进行了重构以演示功能。
Notification
现在使用绑定@bind-ShowAlert="ShowAlert"
。
发生的情况是关闭按钮单击将
false
返回到绑定。 这会在父级中设置 ShowAlert
。 回调是一个 UI 事件,因此会触发父级的渲染。 ShowAlert
已更改,渲染器检测到并使用新的 Notification
值调用 false
。 它呈现并隐藏其内容。
@page "/"
<PageTitle>Home</PageTitle>
<Notification @bind-ShowAlert="@ShowAlert" AlertClass="@AlertClass" AlertMessage="@AlertMessage" />
<div class="m-2">
<button class="btn btn-success" @onclick="() => this.CheckProductVersion(true)">Check Version Success</button>
<button class="btn btn-danger" @onclick="() => this.CheckProductVersion(false)">Check Version Failure</button>
<button class="btn btn-dark" @onclick="this.CloseNotification">Close Notification</button>
</div>
@code
{
private bool ShowAlert { get; set; }
private string AlertClass { get; set; } = "alert-info";
private string? AlertMessage { get; set; }
private async Task CheckProductVersion(bool error)
{
await Task.Delay(100);
if (error)
{
//await UpdateWorker.CheckUpdate();
ShowAlert = true;
AlertClass = "alert-success";
AlertMessage = "version updated";
}
else
{
ShowAlert = true;
AlertClass = "alert-danger";
AlertMessage = "error in update version";
}
}
private void CloseNotification()
{
this.ShowAlert = false;
}
}