如何在Blazor WASM组件调用中使用context关键字实现行点击传参
解决方案
你不能在组件的OnClick参数绑定中直接使用context,因为context仅在RenderFragment<TItem>(也就是<Body>、<Details>这类内部块)的作用域内有效,组件根节点的OnClick绑定不在这个作用域里。
核心修改点
组件已经通过EventCallback<TItem>正确传递了当前行的item,你只需要在子页面的OnClick回调中接收这个item,再提取你需要的DistributionShipment对象即可:
修改子页面的组件调用:
将OnClick="()=>getShipment(context)"替换为直接接收item参数,从KeyValuePair中取出Key(即DistributionShipment)传入getShipment。优化详情展示逻辑(可选):
原<Details>块的判断逻辑可以简化,直接利用当前行的context.Key与选中的detailShipment对比。
修改后的子页面代码
<Component TItem=@(KeyValuePair<DistributionShipment, int>) Items="@distributionShipmentsItemCount.ToList()" OnClick="@(item => getShipment(item.Key))"> <!-- 直接接收item参数 --> <Header> <tr> <th>Shipment-ID</th> <th style="color:gold;">DestinationBranch</th> <th style="color:dodgerblue;">ItemCount</th> <th style="color:forestgreen;">Status</th> <th></th> </tr> </Header> <Body> <td> @context.Key.ID.Convert("distributionShipment") </td> <td> @context.Key.DestinationBranch </td> <td> @context.Value </td> <td> @context.Key.State </td> <td> <button type="button" class="btn btn-info" @onclick="()=>getShipment(context.Key)">Details</button> </td> </Body> <Details> <!-- 简化判断逻辑 --> @if (detailShipment != null && detailShipment.ID == context.Key.ID) { <DetailShipmentInfo shipment="@detailShipment"></DetailShipmentInfo> } </Details> </Component> @code{ private DistributionShipment detailShipment = new DistributionShipment(); private Dictionary<DistributionShipment, int> distributionShipmentsItemCount = new Dictionary<DistributionShipment, int>(); private void getShipment(DistributionShipment distributionShipment) { detailShipment = distributionShipment; StateHasChanged(); } }
组件无需修改的原因
你的组件代码已经正确实现了以下逻辑:
- 遍历
Items时给每个<tr>绑定@onclick="()=>select(item)" select方法通过EventCallback<TItem>.InvokeAsync(item)将当前行的item传递给子页面的回调- 这种设计保持了组件的复用性,无论
TItem是什么类型,子页面都可以通过回调接收并处理对应的对象
内容的提问来源于stack exchange,提问作者meszyyy
相关产品推荐
相关产品推荐

