@page "/ParentComponent"
<h3>Parent Component</h3>
<p>String in Parent:@parentString</p>
<button @onclick="@PassToChild">Pass String To</button>
<ChildComponent
ToChild=@parentString
FromChild=@ReceivedFromChild>
</ChildComponent>
@code {
private string parentString = "Initial Parent String";
private void PassToChild()
{
parentString += "_ To Child";
}
//委托方法,用于传递给子组件
private void ReceivedFromChild(string str)
{
parentString = str;
StateHasChanged();//使用最新的数据状态刷新UI
}
}
<h4>Child Component</h4>
<button @onclick="@PassToParent">Pass String to Parent</button>
<p>String received from Parent :@ToChild</p>
@code {
[Parameter]
private string ToChild { get; set; }
//委托参数,组件之间使用委托传递方法
[Parameter]
Action<string> FromChild { get; set; }
private string childString;
private void PassToParent()
{
childString = ToChild + "_ To Parent";
FromChild(childString);//调用委托
}
}