如何在加载组件时触发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);
}
}
答案 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();
}
}