如何通过Blazor EventCallback实现子组件向父组件传递多参数?
.NET 8.0.2下Blazor通过EventCallback传递多参数的可行方案
之前在Blazor中使用EventCallback实现子组件向父组件传递多个参数时遇到了不少麻烦,这里分享.NET 8.0.2环境下验证可行的实现方案:
子组件代码
(ListItem_DC是需要和其他布尔类型参数一起传递给父组件的自定义对象)
<button class="my-button" @onclick="@(() => OnClickMoveHandler(Item, true, false))" >1 Up</button> <button class="my-button" @onclick="@(() => OnClickMoveHandler(Item, false, false))" >1 Down</button> <button class="my-button" @onclick="@(() => OnClickMoveHandler(Item, true, true))" >To top</button> <button class="my-button" @onclick="@(() => OnClickMoveHandler(Item, false, true))" >To bottom</button> @code { [Parameter] public ListItem_DC Item { get; set; } [Parameter] public EventCallback<(ListItem_DC, bool, bool)> OnClickMove { get; set; } protected virtual async Task OnClickMoveHandler(ListItem_DC item, bool directionUp, bool toTheTopOrBottom) { await OnClickMove.InvokeAsync((item, directionUp, toTheTopOrBottom)); } }
父组件代码
... <ChildComponent Item="@context" OnClickMove="MoveItemHandler" /> ... @code { private async Task MoveItemHandler((ListItem_DC item, bool directionUp, bool toTheTopOrBottom) args) { // 这里编写参数处理逻辑 await MoveItem(args.item, args.directionUp, args.toTheTopOrBottom); } }
我曾参考过相关技术讨论话题,但没找到清晰可直接复用的示例,因此整理分享这个方案。该方案能成功运行的核心在于:父组件绑定事件时直接使用方法名OnClickMove="MoveItemHandler",同时对应的处理方法使用具名元组来接收多个参数,避免了额外创建实体类的麻烦。
内容的提问来源于stack exchange,提问作者Jiri Klokocka
相关产品推荐
相关产品推荐

