在 Blazor 中从父母到孩子沟通

问题描述 投票:0回答:1

考虑父 MainPage.razor 和子 ChildComponent.razor。现在,当我单击 MainPage.razor 中的按钮时,我想与 ChildComponent.razor 进行通信。

可能想像 ChildComponent.razor.cs 中的方法一样访问,因为我需要将一些信息从 child 发送到 MainPage。我明白我可以执行 EventCallBack 并将数据传递回 MainPage。如何从 MainPage 到 ChildComponent 进行通信?

c# .net asp.net-core events blazor
1个回答
0
投票

您只需在 MainPage.razor 中使用

ChildComponent child1;
创建一个“child1”实例。然后确保您使用的任何 ChildCompoent 都通过
<ChildComponent @ref="child1" />
引用此实例。您可以尝试以下操作:
ChildComponent.rzor

//The value could be changed by click
<button @onclick="@(()=>{ChildInfo="new value";})">Child changeValue</button>
@code {
    public string ChildInfo { get; set; } = "old value";

}

主页.razor

@page "/"
<button @onclick="GetInfo">Get Child</button>
<ChildComponent @ref="child1" />    @* Any ChildCompnent you are using reference to "child1" *@

@Information

@code {
    private string Information;

    ChildComponent child1;  // Create a specified instance named "child1"
    private void GetInfo()
    {     
        Information = child1.ChildInfo;
    }
}

点击“Get Child”你会看到“old value”;单击“Child changeValue”后,再次单击“Get Child”,您将看到“新值”。

© www.soinside.com 2019 - 2024. All rights reserved.