【问题标题】:Blazor make element disappear after x secondsBlazor 使元素在 x 秒后消失
【发布时间】:2021-08-31 04:43:51
【问题描述】:

我构建了一个通知系统,它在 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;
}

【问题讨论】:

    标签: c# blazor .net-5


    【解决方案1】:
    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 LifeCycle 的事件。

    Task.Delay() 创建暂停但也允许呈现新状态。

    【讨论】:

    • 没想到这么简单。我预计 task.delay 会阻止 UI 2 秒。谢谢!
    • 一个 Thread.Sleep() 会阻塞。 Blazor UI 和 LifeCycle 很大程度上依赖于 async/await。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2020-05-07
    • 2023-03-19
    • 2018-01-11
    相关资源
    最近更新 更多