Blazor 如何知道EventCallback何时被触发?
我正在使用razor组件进行一些测试,但是我在将属性从子组件更新为父组件时遇到了一个问题 当父组件更新属性时,我使用EventCallback更新父组件。它适用于具有两个级别(ParentComponent/ChildComponent)的体系结构,但不适用于三个级别(祖父母组件/ParentComponent/ChildComponent) 让我们以三个组件A、B和C为例Blazor 如何知道EventCallback何时被触发?,blazor,razor-components,Blazor,Razor Components,我正在使用razor组件进行一些测试,但是我在将属性从子组件更新为父组件时遇到了一个问题 当父组件更新属性时,我使用EventCallback更新父组件。它适用于具有两个级别(ParentComponent/ChildComponent)的体系结构,但不适用于三个级别(祖父母组件/ParentComponent/ChildComponent) 让我们以三个组件A、B和C为例 - A (GrandParentComponent) -- B (ParentComponent) --- C (Chil
- A (GrandParentComponent)
-- B (ParentComponent)
--- C (ChildComponent)
- 更新B将触发EventCallback以更新A
- 更新C将触发EventCallback以更新B,但是在此阶段,B在更新后不会触发EventCallback,因此A组件仍然没有更新
来自组件A@Message的消息
@代码{
私有字符串消息;
私有任务mymethod(字符串str)
{
信息=str;
返回Task.CompletedTask;
}
}
部件B.剃须刀
来自组件B@Message的消息
@代码{
字符串myvalue;
[参数]
public EventCallback ComponentEvent{get;set;}
私有字符串消息;
专用异步任务mymethod(字符串str)
{
信息=str;
if(ComponentBEvent.HasDelegate)
{
wait组件bevent.InvokeAsync(str);
}
}
}
组件C.剃须刀
来自组件C@myvalue的消息
@代码{
字符串myvalue;
[参数]
公共事件回调组件事件{get;set;}
}
用法
注意:您可以使用采用状态模式的通知程序服务实现此行为。此服务控制对象的状态、更新、删除等,并定义在操作发生时触发的事件,例如,在组件A中添加了employee对象,在这种情况下,notifier服务将此事实通知所有相关方(订阅组件)
希望这有助于
<ComponentB ComponentBEvent="EventCallback.Factory.Create<string>(this,
mymethod)"></ComponentB>
<p>Message from Component A @message</p>
@code {
private string message;
private Task mymethod(string str)
{
message = str;
return Task.CompletedTask;
}
}
<ComponentC ComponentCEvent="EventCallback.Factory.Create<string>(this,
mymethod)"></ComponentC>
<p>Message from Component B @message</p>
@code {
string myvalue;
[Parameter]
public EventCallback<string> ComponentBEvent { get; set; }
private string message;
private async Task mymethod(string str)
{
message = str;
if(ComponentBEvent.HasDelegate)
{
await ComponentBEvent.InvokeAsync(str);
}
}
}
<input type="text" value="@myvalue" @oninput="@((args) => { myvalue =
args.Value.ToString(); ComponentCEvent.InvokeAsync(args.Value.ToString());
})" />
<p>Message from Component C @myvalue</p>
@code {
string myvalue;
[Parameter]
public EventCallback<string> ComponentCEvent { get; set; }
}
<ComponentA />