Blazor - Add/load 个动态组件

Blazor - Add/load components dynamically

我想我现在犯了一个错误。我有一个覆盖组件。这会覆盖所有内容并可以动态显示内容。

导航中有按标签过滤界面的功能。单击此按钮时,应显示此覆盖组件。

据我目前所知,只有一种解决方法: 动态添加和删除组件。所以组件一直存在,只是动态显示和隐藏。

我现在已将可见性绑定到 属性。到目前为止效果很好,但我想知道如何处理数据。我一直想在视图上查看数据库中的当前数据。

我现在的想法是,每次 Visible 属性 设置为 true 时,都会从数据库重新加载数据。但随后我将不得不以某种方式重新呈现组件或重新加载子内容。或者你会如何解决这个问题?

您在这里遇到了传统的 jQuery/JavaScript 方法:“根据需要呈现内容和 show/hide。”

So the component is always present, but is dynamically displayed and hidden.

这就是你要求 Blazor 做的。

Blazor 可以根据需要动态 add/remove 内容和组件。在上面的示例中,我会将 <div hidden="@Visible"> 替换为..

@if(Visible) 
{
  <content goes here.. />
}

这告诉 Blazor 仅当变量 Visible 为 true 时才呈现内容 。根据评论,使用浏览器工具检查呈现的 HTML,您会看到没有内容发送到浏览器。

您引用的“动态组件”用于在运行时才知道类型时呈现组件(请参阅我在 https://github.com/conficient/BlazorDynamicList). These are now part of NET 6.0 as a supported feature: link

上的示例

我不太确定您要实现的目标,因此这是对如何动态操作 on/off 组件和 Razor 标记块显示的问题的简单回答。在 Blazor 中,您不需要操纵 display Css 来打开和关闭块。你可以在代码中做到这一点。当 Display 为 false 时,component/razor 不存在于 DOM.

OnOffComponent

@if (this.Display)
{
    <h3>OnOffComponent</h3>
}

@code {
    [Parameter] public bool Display { get; set; }
}

打开关闭视图

@page "/onoff"
<div>
    <button class="btn btn-dark" @onclick="Switch">Toggle</button>
</div>

@if (_display)
{
    <h3>Hello World</h3>
}

<OnOffComponent Display="this._display"></OnOffComponent>

@code {
    private bool _display = false;

    private void Switch(MouseEventArgs e)
        => _display = !_display;
}

从数据库重新加载数据时,可以在组件初始化时获取数据,保存在组件中,显示或不显示。在上面的代码中 OnOffComponent 存在于页面中,无论是否显示任何内容。

如果您将组件包裹在 @if (this.Display) 中,如下所示,那么每次切换显示时它都会被销毁并重新创建。

@if (_display)
{
    <h3>Hello World</h3>
    <OnOffComponent Display="this._display"></OnOffComponent>
}