Blazor事件回调仅在设置了事件回调时执行一次



在bazor-wasm中,我正在制作一个分页器组件,为表组件添加分页。分页器组件接受一个事件回调(PageChanged(,该回调在用户更改页面时执行。

这是的视图

<div id="paginator-container">
<div id="paginator-controls">
<button type="button"
class="btn btn-action"
@onclick="@this.GoToFirstPage"
disabled="@this.IsFirstPage">
<i class="fas fa-angle-double-left"></i>
</button>
<button type="button"
class="btn btn-action"
@onclick="@this.GoToPreviousPage"
disabled="@this.IsFirstPage">
<i class="fas fa-angle-left"></i>
</button>
<span>
page @this.CurrentPage of @this.PageCount
</span>
<button class="btn btn-action"
@onclick="@this.GoToNextPage"
disabled="@this.IsLastPage">
<i class="fas fa-angle-right"></i>
</button>
<button class="btn btn-action"
@onclick="@this.GoToLastPage"
disabled="@this.IsLastPage">
<i class="fas fa-angle-double-right"></i>
</button>
</div>

以及相关代码

public partial class Paginator
{
[Parameter]
public int Lenght { get; set; }
[Parameter]
public EventCallback<InnosysPaginatorContext> PageChanged { get; set; }
[Parameter]
public int PageSize { get; set; } = 50;
private int CurrentPage { get; set; }
private int PageCount { get; set; }
private bool IsFirstPage
=> this.CurrentPage == 1;
private bool IsLastPage
=> this.CurrentPage == this.PageCount;
protected override void OnParametersSet()
{
this.SetPageCount();
this.CurrentPage = 1;
base.OnParametersSet();
}
private void SetPageCount()
{
decimal pageCount = (decimal)this.Lenght / this.PageSize;
if (pageCount != Math.Floor(pageCount))
{
pageCount = Math.Floor(pageCount + 1);
}
this.PageCount = (int)pageCount;
}
private async Task GoToFirstPage()
=> await this.GoToPage(1);
private async Task GoToPreviousPage()
=> await this.GoToPage(this.CurrentPage - 1);
private async Task GoToNextPage()
=> await this.GoToPage(this.CurrentPage + 1);
private async Task GoToLastPage()
=> await this.GoToPage(this.PageCount);
private Task GoToPage(int pageIndex)
{
this.CurrentPage = Math.Clamp(pageIndex, 1, this.PageCount);
return this.ExecutePageChangedEvent();
}
private async Task ExecutePageChangedEvent()
=> await this.PageChanged.InvokeAsync(new InnosysPaginatorContext
{
CurrentPage = this.CurrentPage,
PageSize = this.PageSize
});
}

当我在不设置PageChanged的情况下使用分页器时,如下所示:

<Paginator Lenght="300" />

我可以很好地浏览页面。

但是,如果我设置回调,比如这个

<Paginator Lenght="300"
PageChanged="@this.OnPageChangedTest" />
<p>Page: @pageIndex</p>
<p>page size: @pageSize</p>
@code{
int pageIndex = 1;
int pageSize = 50;
void OnPageChangedTest(InnosysPaginatorContext innosysPaginatorContext)
{
pageIndex = innosysPaginatorContext.CurrentPage;
pageSize = innosysPaginatorContext.PageSize;
}
}

按钮只工作一次,我只能进入第2页。随后单击下一页的按钮会执行回调,但分页器的CurrentPage被卡在第2页上。为什么会发生这种情况?

问题必须在这里:

this.CurrentPage = 1; 

每当执行OnParametersSet时执行;实际上,您不需要将CurrentPage设置为1。如果只需要执行一次,则应该在OnInitialized(Async(对中执行

protected override void OnParametersSet()
{
this.SetPageCount();
//  this.CurrentPage = 1;
base.OnParametersSet();
}

相关内容

  • 没有找到相关文章

最新更新