考虑父 MainPage.razor 和子 ChildComponent.razor。现在,当我单击 MainPage.razor 中的按钮时,我想与 ChildComponent.razor 进行通信。
可能想像 ChildComponent.razor.cs 中的方法一样访问,因为我需要将一些信息从 child 发送到 MainPage。我明白我可以执行 EventCallBack 并将数据传递回 MainPage。如何从 MainPage 到 ChildComponent 进行通信?
您只需在 MainPage.razor 中使用
ChildComponent child1;
创建一个“child1”实例。然后确保您使用的任何 ChildCompoent 都通过 <ChildComponent @ref="child1" />
引用此实例。您可以尝试以下操作://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”,您将看到“新值”。