在应用程序启动时调用代码方法(无需调用@onclick)

时间:2020-02-12 18:16:42

标签: blazor

如何在加载组件时触发StartClock()函数,而不必调用@onclick事件?

@page "/clock"
@using System.Threading;

<p @onclick=@StartClock>@currenttime</p>

@code
 {
    string currenttime = DateTime.Now.ToString("dd/mm/yyyy HH:mm:ss");

    void StartClock()
    {
        var timer = new Timer(new TimerCallback(_ =>
        {
            InvokeAsync(() => {
                currenttime = DateTime.Now.ToString("dd/mm/yyyy HH:mm:ss");
                StateHasChanged();
            });
        }), null, 1000, 1000);
    }
}

1 个答案:

答案 0 :(得分:0)

这是@Rich Bryant回答后的更新代码

@page "/clock"
@using System.Threading;

<p>@currenttime</p>

@code
 {
    private string currenttime = DateTime.Now.ToString("dd/mm/yyyy HH:mm:ss");

    private void StartClock()
    {
        var timer = new Timer(new TimerCallback(_ =>
        {
            InvokeAsync(() =>
            {
                currenttime = DateTime.Now.ToString("dd/mm/yyyy HH:mm:ss");
                StateHasChanged();
            });
        }), null, 1000, 1000);
    }

    protected override void OnAfterRender(bool firstRender)
    {
        StartClock();
    }
}