Blazor Wasm通知父组件状态变化



需要哪些代码才能使Blazor子组件通知其父组件状态变化?我尝试了以下操作,但没有成功:

助手类

public class NotificationHandler
{
public event Action? Dispatcher;
public void Notify() => Dispatcher?.Invoke();
public void Attach(Action dispatcher) => Dispatcher += dispatcher;
public void Release(Action dispatcher) => Dispatcher -= dispatcher;
}

父组件

@code
{
ChildComponent childComponent;
StateNotifier stateNotifier;
protected override Task OnInitializedAsync()
{
stateNotifier.Attach(StateHasChanged);
return base.OnInitializedAsync();
}

// Overloading StateHasChanged() - does it work this way?
protected new void StateHasChanged() // never gets called
{
DoSomething(); 
base.StateHasChanged();
}
}
<div>
<ChildComponent StateNotifier="stateNotifier" />
</div>

子组件

@code
{
[Parameter]
public StateNotifier stateNotifier { get; set; }
async void OnSomeUserAction()
{
stateNotifier.Notify();
}
}

需要哪些代码才能使Blazor子组件通知其状态的父组件改变了?

最简单的方法是使用EventCallback。

子组件

<button @onclick=NotifyParent>Notify</button>
@code {
[Parameter] public EventCallback OnSomethingHappened { get; set; }
async Task NotifyParent()
{
await OnSomethingHappened.InvokeAsync();
}
}

父组件

<ChildComponent OnSomethingHappened=@HandleSomethingHapppened />
@code {
async Task HandleSomethingHappened()
{
await DoSomethingElse();

// StateHasChanged() not needed when handling an event
// The Blazor engine will automatically
// run an Html diff after handling a component
// event.
// StateHasChanged();
}
}

最新更新