响应来自 parent 组件的 child-emitted 事件

Responding to child-emitted events from parent component

我有 2 个组件 ABBA 的 child。有没有像 EventEmitter (Angular) 在 Blazor 中?我如何在 parent 中附加一个事件处理程序来响应其 child 的输出?

Child

<button onclick="Emit">Press me</button>
@functions(){
[Parameter] // i do not know how the `Output` is called
private string Pressed {get;set;}
public void Emit()
{
  //somehow emit `Pressed` to the parent , make him respond
}
}

Parent分量

<Child [Pressed]="doSomething"> </Child>
@functions{
 doSomething(string value){
  Console.WriteLine("Child sent me : "+value);
 }
}

P.S 抱歉语法错误,我是 blazor 的新手。

您可以使用 Action 参数

<button onclick="Emit">Press me</button>
@functions(){
[Parameter] protected Action<string> Pressed {get;set;}

public void Emit()
{
  Pressed?.Invoke("Some String");
}
}

在 Emit 中,您使用条件检查是否有人订阅了 Action 并调用它,传入参数。

别忘了,在Parent中,如果要更新页面,在"doSomething"方法中调用StateHasChanged()

组件A.cshtml

// Define a method in the parent component which will be called 
// from the child component when the user tap the button residing 
// in the child component. This method has a string parameter passed
// from the child component
public void GetValueFromChild(string value)
 {
        // Do somethig with value
  } 

组件B.cshtml


// When the user click the button the method GetValueFromChild
// defined on the parent component is called

<button class="btn" onclick=@(() => OnAddValue("some string value"))>Add</button>

    @functions
{
    // Define an Action delegate property which stores a reference
    // to A.GetValueFromChild
    // Parameters
    [Parameter] Action<string> OnAddValue{ get; set; }
}

A.cshtml

// Here (in the parent component) you place the child component and
// set its OnAddValue to the name of the method to be called
<B OnAddValue = "GetValueFromChild"></B> 

如果对您有帮助,请采纳我的回答
希望这有助于...