【问题标题】:Blazor - Is it possible to trigger a function in page component from MainLayoutBlazor - 是否可以从 MainLayout 触发页面组件中的功能
【发布时间】:2020-07-17 15:43:28
【问题描述】:

我的MainLayout.razor 组件中有一个侧边抽屉,用于设置/更改某些值,然后在整个应用程序中使用这些值。

<CascadingValue Value="@appValues" Name="AppValue">
    <SideDrawer OnUpdate="@RefreshPage"></SideDrawer>
    <div class="content px-4">
        @Body
    </div>
</CascadingValue>

当我更新 SideDrawer 中的值时,我会执行 EventCallback,通过它我可以更新变量,然后这些变量可以用作整个页面组件的级联值。

@code{
    public AppValues appValues = new AppValues();
    protected void RefreshPage()
    {
        appValues.value1 = somevaluefromsidedrawer;
        appValues.value2 = someothervaluefromsidedrawer;
        StateHasChanged();
    }
}

并且这些级联值在页面组件中更新得很好。但问题是,在页面组件中,有一种方法(比如LoadData())应该根据这些级联值更新某些数据集。

@code{
    [CascadingParameter(Name = "AppValue")]
    protected AppValues appValues { get; set; }
    protected void RefreshCurrentPage()
    {
        LoadData(appValues.value1);
    }
}

理想情况下,我希望能够从MainLayout.razor组件中的RefreshPage()方法调用页面组件中的RefreshCurrentPage()方法,这样页面组件中的所有数据集都会根据更新后的内容进行刷新价值观。

有可能做这样的事情吗?

【问题讨论】:

  • 您可以查看this blog post,它概述了一种相当简单的方法来触发更远的 DOM 树上的渲染。您可能会看到的第二件事是使用服务来触发重新渲染。我有一个答案here,应该可以让你指出正确的方向。
  • 感谢@NikP。我将开始研究您和 enet 的答案,看看哪个更适合我的需要。但它们在学习做这些事情的新方法方面非常有帮助。

标签: blazor blazor-server-side


【解决方案1】:

您可以通过多种方式做到这一点:

您可以将 MainLayout 组件的引用以 CascadingValue vomponent 的形式传递给感兴趣的子组件,如下所示:

<CascadingValue Value="this" Name="TheMainLayout">
    
</CascadingValue>

子组件应该像这样获取引用:

@code{
    [CascadingParameter(Name = "TheMainLayout")]
    public MainLayout MainLayout { get; set; }
    
}

并将自身添加到 MainLayout 组件中定义的组件列表中:

 // Child component adds itself to the  MainLayout component
    protected override void OnInitialized()
    {
        MainLayout.AddPage(this);
    }

在 MainLayout 组件中,您将定义一个 ComponentBase 对象列表, 和AddPage方法如下:

public void AddPage(ComponentBase page)
{
    // Code to add the page component to the list
}

既然MainLayout保存了对组件的引用,它可以直接调用每个添加的页面组件中定义的RefreshCurrentPage(我猜它只能是一个,因为我们在谈论可路由组件,对吧)。

注意:以上只是解决方案的概要。您可以扩展它以提供每次需要刷新数据时引发的事件,并且每个页面组件都应订阅该事件,当引发该事件时,调用 RefreshCurrentPage 方法。这是一种比直接从 MainLayout 调用 RefreshCurrentPage 更好、更复杂的方法。

您应该提供代码以从组件列表中删除添加的组件引用,当这些组件被终止时等。

请注意,不再需要 appValues 的 CascadingValue,因为子组件持有对 MainLayout 的引用并且可以直接访问这些值。

注意:以上所有过程都可以通过注入 MainLayout 组件及其子组件的服务类来实现。

久等了,伙计……

【讨论】:

    猜你喜欢
    • 2020-01-27
    • 2012-05-26
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2020-07-10
    相关资源
    最近更新 更多