从嵌入式 Blazor 组件检索数据

Retrieve data from embedded Blazor component

我想创建一个Blazor组件,其中弹出一个组件(a.k.a一个对话框)给用户(弹出的组件会嵌入到主组件中),然后在用户从嵌入对话框组件中选择一个项目,父组件将收到通知,并能够从嵌入组件中检索选择数据,就像桌面应用程序中的对话框一样。

我想要的伪代码示例:

<h1>main component</h1>
<EmbedComponent></EmbedComponent>
@code
{
   private void OnSelection(Item selectedItem ){}
}
<h1>embed component</h1>
<h1>please choose:</h1>
<button @onclick="NotifyParent(item1)">option1<button>
<button @onclick="NotifyParent(item2)">option2<button>

我该怎么做(在 Blazor WebAssembly 中)?

您想使用 EventCallback

监听 parent 中的事件:

<h1>main component</h1>
<EmbededComponent OnSelection="OnSelection" />
@code
{
   private void OnSelection(Item selectedItem ){}
}

接收回调作为参数并从child触发:

<h1>embeded component</h1>
<h1>please choose:</h1>
<button @onclick="() => NotifyParent(item1)">option1<button>
<button @onclick="() => NotifyParent(item2)">option2<button>

@code {
    [Parameter]
    public EventCallback<Item> OnSelection { get; set; }

    public async Task NotifyParent(Item item) {
        if (OnSelection.HasDelegate) {
            await OnSelection.InvokeAsync(item); 
        }
    }
}