在 Blazor 中几秒钟后关闭模式

Close a modal after a few seconds in Blazor

所以基本上我想在用户点击按钮时显示一个模式,以显示操作是否成功或是否存在问题。但几秒钟后我想关闭它,这样用户就不必每次都手动关闭它。有没有办法在不暂停整个程序几秒钟的情况下执行此操作?还是有更好的方式向用户显示消息而不是模式?

现在我得到了这两种打开和关闭模态的方法:

    public void Open(string title, string message)
    {
        ModalDisplay = "block;";
        ModalClass = "Show";
        ShowBackdrop = true;
        ModalTitle = title;
        ModalBody = message;
        StateHasChanged();
    }

    public void Close()
    {
        ModalDisplay = "none";
        ModalClass = "";
        ShowBackdrop = false;
        StateHasChanged();
    }

所以我已经解决了我的问题并添加了一个计时器,所以现在在我显示对话框后我启动一个计时器 2 秒,当计时器到期时它会执行一个隐藏模态的方法:

    private void ToggleModal(string title, string message)
    {
        //Showing modal
        ModalDisplay = "block;";
        ModalClass = "Show";
        ShowBackdrop = true;
        ModalTitle = title;
        ModalBody = message;
        StateHasChanged();

        //Hiding modal
        Timer timer = new Timer();
        timer.Interval = 2000;
        timer.Elapsed += OnTimedEvent;
        timer.AutoReset = false;
        timer.Enabled = true;

    }

    private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        InvokeAsync(() => {
            ModalDisplay = "none";
            ModalClass = "";
            ShowBackdrop = false;
            StateHasChanged();
        });
    }

可能有更好的方法来实现这一点,但这是目前对我有用的方法!

如果你的 event/method 可以是异步的,你可以跳过计时器而只使用 Task.Delay(milliseconds),比如

   public async Task Open(string title, string message)
    {
        ModalDisplay = "block;";
        ModalClass = "Show";
        ShowBackdrop = true;
        ModalTitle = title;
        ModalBody = message;
        StateHasChanged();

        await Task.Delay(2000);
        ModalDisplay = "none";
        ModalClass = "";
        ShowBackdrop = false;
        StateHasChanged();
    }

我没有模式,而是在页面上呈现了 div。这是剃刀组件:

@if (!string.IsNullOrWhiteSpace(Text))
{
    <div class="alert @alertClass">@Text</div>
}


@code {
    private string messageType;
    private string alertClass = "alert-info";

    [Parameter] public string Text { get; set; }

    protected override async Task OnParametersSetAsync()
    {
        await Task.Delay(2000);
        Text = "";
    }

    [Parameter]
    public string MessageType
    {
        get { return messageType; }
        set
        {
            messageType = value;
            switch (messageType)
            {
                case "Error":
                    alertClass = "alert-danger";
                    break;
                case "Warning":
                    alertClass = "alert-warming";
                    break;
                case "Success":
                    alertClass = "alert-success";
                    break;
                default:
                    break;
            }
        }
    }
}

用法:

<AlertMessage Text="Lorem ipsum dolor sit amet." MessageType="Error"/>