【问题标题】:Responding to child-emitted events from parent component响应来自父组件的子事件
【发布时间】:2019-01-23 12:37:48
【问题描述】:

我有 2 个组件 ABBA 的孩子。Blazor 中是否有类似 EventEmitter (Angular) 的东西?如何在父级中附加一个可以响应其子级输出的事件处理程序?

儿童

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

父组件

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

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

【问题讨论】:

    标签: c# eventemitter blazor


    【解决方案1】:

    可以使用 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()。

    【讨论】:

    • 但是Action没有输出。我怎样才能得到父动作的content?你能用Func&lt;string&gt;吗?
    • action 是你的父方法,它不需要返回值。试试看。
    【解决方案2】:

    组件 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> 
    

    如果对您有帮助,请将我的回答标记为已接受
    希望这会有所帮助...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      • 1970-01-01
      • 2020-03-29
      • 2019-04-05
      • 2017-02-26
      • 1970-01-01
      相关资源
      最近更新 更多