首页 > 解决方案 > 如何在子组件中访问父组件类型?

问题描述

在子组件中,如何访问对父组件的引用?如果它嵌套在特定类型的父级中,我需要在子级中执行特定操作。

<MyParentComponent>
    <MyChildComponent></MyChildComponent>
</MyParentComponent>

标签: c#asp.net-coreblazor

解决方案


有很多方法可以做到这一点。

如果您只需要父级的一个属性/方法,您可以为该属性/方法传递一个参数,如您在docs中所见。

如果你想要整个父母,你可以使用 aCascadingValue和 pass this

例如

MyParentComponent.razor

<CascadingValue Value="this">
    @ChildContent
</CascadingValue>

在 中MyChildComponent,您可以通过CascadingParameter.

[CascadingParameter]
public MyParentComponent MyParentComponent { get; set; }

如果子组件不是父组件的直接子组件并且您不想跨嵌套组件传递多个参数,这将是获取父引用的好方法。


推荐阅读