如何知道何时触发EventCallback?

问题描述 投票:0回答:1

我正在使用剃须刀组件进行一些测试,但在将属性从子组件更新为祖父母组件时遇到问题。

当子组件更新属性时,我正在使用EventCallback更新我的父组件。它适用于具有两个级别(ParentComponent / ChildComponent)的体系结构,但是不适用于具有三个级别(GrandParentComponent / ParentComponent / ChildComponent)的体系结构。

让我们以包含A,B和C的三个组件为例。

- A (GrandParentComponent)
-- B (ParentComponent)
--- C (ChildComponent)
  • 更新B将触发EventCallback来更新A
  • 更新C将触发EventCallback来更新B,但是在此阶段,B一旦更新就不会触发EventCallback,因此A组件仍未更新。

您如何知道某个组件是否已被EventCallback更新。

我想知道,因此当从C触发EventCallback时,可以从B触发EventCallback。是否有意义? :D

blazor razor-components
1个回答
0
投票

如何知道何时触发EventCallback?

定义一个事件委托,您可以在触发EventCallback时触发它……只是开个玩笑。

您可以通过多种方式进行操作。这是一个:

ComponentA.razor

<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;
   }
}

ComponentB.razor

<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);
        }
    }
 }

ComponentC.razor

<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 />

注意:您可以使用通告程序服务来实现此行为,该服务采用状态模式。此服务控制对象的状态,更新,删除等,并定义在操作发生时触发的事件,例如,在组件A中添加了一个雇员对象,在这种情况下,通知程序服务会通知所有相关方(订阅组件) )的事实。

希望这有帮助...

© www.soinside.com 2019 - 2024. All rights reserved.