ASP.NET Core Blazor三层嵌套组件双向通信实现方法
Blazor 代码后置模式三级嵌套组件双向通信实现
核心实现逻辑基于TaskCompletionSource做异步交互等待,无需第三方状态管理,直接通过组件引用调用公开方法,符合代码后置开发规范。
1. 子组件2(确认弹窗组件)
负责渲染确认弹窗UI,接收唤起指令,返回用户点击结果。
Child2.razor
@if (IsVisible) { <div style="position:fixed;inset:0;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;"> <div style="background:#fff;padding:2rem;border-radius:8px;min-width:300px;"> <p>请确认是否提交当前操作?</p> <div style="text-align:right;margin-top:1rem;"> <button @onclick="() => Close(false)" style="margin-right:0.5rem;">取消</button> <button @onclick="() => Close(true)">确认</button> </div> </div> </div> }
Child2.razor.cs(代码后置)
using Microsoft.AspNetCore.Components; namespace YourProject.Components; public partial class Child2 : ComponentBase { private TaskCompletionSource<bool>? _taskSource; public bool IsVisible { get; private set; } /// <summary> /// 唤起确认弹窗,等待用户操作返回bool结果 /// </summary> public Task<bool> ShowAsync() { _taskSource = new TaskCompletionSource<bool>(); IsVisible = true; StateHasChanged(); return _taskSource.Task; } private void Close(bool status) { IsVisible = false; _taskSource?.TrySetResult(status); StateHasChanged(); } }
2. 子组件1(无UI中间层组件)
无任何UI输出,仅做逻辑透传,承接父组件调用、唤起子组件2、透传返回结果。
Child1.razor
@namespace YourProject.Components @* 仅嵌套子组件2,无其他UI元素 *@ <Child2 @ref="_child2Instance" />
Child1.razor.cs(代码后置)
using Microsoft.AspNetCore.Components; namespace YourProject.Components; public partial class Child1 : ComponentBase { private Child2? _child2Instance; /// <summary> /// 对外暴露给父组件调用的入口方法 /// </summary> /// <param name="inputParam">需要传入的自定义参数</param> public async Task<bool> ExecuteWithConfirmAsync(object inputParam) { // 此处可编写中间层参数校验、逻辑转换代码 if (_child2Instance == null) return false; bool result = await _child2Instance.ShowAsync(); // 此处可编写中间层结果处理代码 return result; } }
3. 父组件实现
通过组件引用调用子组件1的公开方法,等待返回结果后执行后续业务。
Parent.razor
@page "/submit-page" @namespace YourProject.Pages <button @onclick="callChildOne">Submit</button> @* 嵌套子组件1 *@ <Child1 @ref="_child1Instance" />
Parent.razor.cs(代码后置,补全你需要的逻辑)
using Microsoft.AspNetCore.Components; using YourProject.Components; namespace YourProject.Pages; public partial class Parent : ComponentBase { private Child1? _child1Instance; private async Task callChildOne() { if (_child1Instance == null) return; // 传入指定参数,等待子组件链路返回bool结果 bool submitStatus = await _child1Instance.ExecuteWithConfirmAsync(/* 传入你的自定义参数 */); if (submitStatus) { // 用户点击确认,执行提交逻辑 } else { // 用户取消,执行对应逻辑 } } }
注意事项
- 所有上层组件调用下层组件的方法必须声明为
public,@ref引用的实例字段可访问性要匹配 TaskCompletionSource会在用户点击按钮时触发异步任务完成,不会阻塞UI渲染线程- 中间层子组件1无任何UI输出,仅承担逻辑中转职责,符合需求要求
- 若需要传递更多自定义参数、扩展弹窗逻辑,直接在各层公开方法上增加形参透传即可
内容的提问来源于stack exchange,提问作者Kajul Nisha
相关产品推荐
相关产品推荐

