nog*_*ood 21 events call blazor
第一次进入 Blazor。
在开始模板中,我看到事件 btnClicked 是如何工作的。
对于按钮事件,它是这样的:
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
Run Code Online (Sandbox Code Playgroud)
当我不想在点击按钮上调用 IncementCount 时,它是什么代码行
但是在“onload page event”或者这个事件叫什么?
谢谢帮助
Nik*_*k P 31
有两种主要方法可以做到这一点,并且任何一种都可以。我倾向于第一个,但第二个也能完成工作。
第一种方式,在您的@code
块中,您可以覆盖该OnInitialized
方法。我使用异步版本,因为您可以开始您的任务并让页面基础知识加载,然后它会在设置时刷新。
@code {
void SomeStartupMethod()
{
// Do Some Work
}
Task SomeStartupTask()
{
// Do some task based work
return Task.CompletedTask;
}
protected override async Task OnInitializedAsync()
{
SomeStartupMethod();
await SomeStartupTask();
}
Run Code Online (Sandbox Code Playgroud)
这将在页面加载时起作用,例如填充数据的初始服务调用,有条件地填充列表,无论您需要做什么。顺便说一句,我发现的一个技巧是,如果你把await Task.Delay(1);
OnInitializedAsync 方法体的第一行作为第一行,它将打破页面渲染中剩余的执行,因此你可以获得初始和响应页面,而初始加载仍在处理中背景。只是让您的页面响应更快的东西。
第二种方式是重写OnAfterRender
方法,允许页面1完全渲染然后执行。它还有一个默认输入bool firstRender
,您可以将其用作数据加载和其他事情的条件。
protected override void OnAfterRender(bool firstRender)
{
// execute conditionally for loading data, otherwise this will load
// every time the page refreshes
if(firstRender)
{
// Do work to load page data and set properties
}
}
Run Code Online (Sandbox Code Playgroud)
对于此方法,要记住的重要一点是,只要 Blazor 引擎检测到需要刷新 UI,它就会执行,因此请firstRender
明智地使用该参数。
根据您需要做什么,不同的生命周期方法可能在不同的时间有用,还有一些我没有涉及。有关更多信息,请查看官方文档。仅使用文档提供的内容,我就可以自己走得很远,此链接将帮助您开始使用生命周期方法。
希望这可以帮助!
Ali*_*ian 10
[Parameter]
public int StartValue { get; set; }
private int currentCount = 0;
protected override void OnInitialized() // = On Page Load
{
currentCount = StartValue;
IncrementCount();
}
private void IncrementCount()
{
currentCount++;
}
Run Code Online (Sandbox Code Playgroud)
或者如果您不想要第一个 StartValue 只是:
[Parameter]
public int StartValue { get; set; } = 0;
protected override void OnInitialized() // = On Page Load
{
currentCount++;
}
Run Code Online (Sandbox Code Playgroud)
如果你想在组件完成渲染后初始化它(也许你想等待 DOM 加载):
[Parameter]
public int StartValue { get; set; }
private int currentCount = 0;
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
currentCount = StartValue;
IncrementCount();
}
}
private void IncrementCount()
{
currentCount++;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
关于 OnInitializedAsync 需要注意的一件重要事情是该事件可以多次触发。
根据您的应用程序,这可能不是您想要反复触发的东西。
// variable in your page or component
public bool Initialized { get; set; }
// if not initialized
if (!Initialized)
{
// Do your initializations
// This way it only runs once
Initialized = true;
}
Run Code Online (Sandbox Code Playgroud)
其他方式是在组件或页面的构造函数中
这里我有一个名为 Index.razor 的页面和一个名为 Index.razor.cs 的后台代码
在构造函数中
public void Index()
{
// Perform your initializations here
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15054 次 |
最近记录: |