【发布时间】:2021-11-05 04:07:36
【问题描述】:
我想从子组件调用一个方法,我有这段代码
应用状态:
public class AppState
{
public string MyMessage { get; private set; }
public string MyMsgToChildren { get; private set; }
public event Action OnChange;
public void SetMessage(string msg)
{
MyMessage = msg;
NotifyStateChanged();
}
public void SetMessageToChildren(string msg)
{
MyMsgToChildren = msg;
NotifyStateChanged();
}
private void NotifyStateChanged() => OnChange?.Invoke();
}
和子组件#1:
@inject AppState AppState
<p>============================</p>
<h3>#1 Child</h3>
<p>send from Father :<b>@AppState?.MyMsgToChildren</b> </p>
<div class="col-sm-6">
<button @onclick="SetMessage">Send To Parent</button>
</div>
<p>============================</p>
@code {
protected override void OnInitialized()
{
AppState.OnChange += StateHasChanged;
}
public void Dispose()
{
AppState.OnChange -= StateHasChanged;
}
void SetMessage()
{
AppState.SetMessage("Message From Child #1");
}
}
#2 Child 与 #1 的代码相同 我有一个父组件:
@page "/State"
@inject AppState AppState
<p>============================</p>
<h3>Parent</h3>
<p>send from child:<b>@AppState?.MyMessage</b> </p>
<div class="col-sm-6">
<button @onclick="SendMsgTochildren">Send To Parent</button>
</div>
<ChildComponent></ChildComponent>
<Child2Component></Child2Component>
@code {
public string MsgToChildren { get; private set; } = "Hi, Im your father - ";
int i = 0;
protected override void OnInitialized()
{
AppState.OnChange += StateHasChanged;
}
public void Dispose()
{
AppState.OnChange -= StateHasChanged;
}
void SendMsgTochildren()
{
i++;
AppState.SetMessageToChildren(MsgToChildren + i.ToString());
}
/* I want to call this method from Child*/
void TargetMethod(int page)
{
}
}
这个应用程序运行良好,只是我想调用这个方法:“TargetMethod(int page)” 来自我的一个子组件,我还需要传递一个整数参数
我想将此代码用于分页。我尝试制作一个组件(分页)并将其添加到每个表格组件中,分页将成为主要组件的孙子,我知道我可以使用其他方式,但我更喜欢使用状态容器 在分页和其他人之间进行交流
【问题讨论】:
标签: c# asp.net-core components blazor-webassembly