我构建了一个通知系统,它在 NotificationHandler
blazor 组件中显示引导警报 div。这工作正常,但通知保留在那里。我想让这些通知在 x 秒后消失。如何在不阻塞 UI 并确保它在 blazor 渲染线程上执行的情况下执行此操作。
请参阅下面的示例代码:
@inject INotificationHandler Handler;
@foreach (var notification in _notifications)
{
<div class="alert alert-success">
<p>@notification</p>
</div>
}
@code
{
private List<string> _notifications = new ();
protected override void OnInitialized()
{
Handler.OnReceived += OnReceived;
}
private async Task OnReceived(string notification)
{
await InvokeAsync(() => {
_notifications.Add(notification);
StateHasChanged();
// TODO: remove notification the _notifications after x seconds
});
}
}
public interface INotificationHandler
{
public event Func<string Task> OnReceived;
}
最佳答案
await InvokeAsync(async () => // note the 'async'
{
_notifications.Add(notification);
StateHasChanged();
// TODO: remove notification the _notifications after x seconds
await Task.Delay(2_000); // x = 2
_notifications.Remove(notification);
StateHasChanged();
});
需要调用 StatehasChanged(),因为 OnReceived() 是一个不属于正常 Blazor 生命周期的事件。
Task.Delay() 创建暂停,但也允许呈现新状态。
关于c# - Blazor 使元素在 x 秒后消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67984436/