简体   繁体   中英

Blazor Repeatable EventCallback for Menu Item

I am working on a repeatable "Card" component that has a list of menu items and actions that this menu can take. However I cannot get the functionality to work. I am coming from React where something like this is quite common but cannot convert my thinking to Blazor. Help is appreciated.

Parent Component:


<Card Title="TestTitle" MenuActions=@MenuActions />

@code{

    public Dictionary<string, EventCallback> MenuActions = 
          new Dictionary<string, EventCallback>(){
            {"Test Case", HandleTestCase},
    }
    public void HandleTestCase(){
        Console.WriteLine("Test Case");
    }
}

Child Component:

<div>
<h2>@Title</h2>
<ul>
   @foreach(var(menuTitle, menuAction) in MenuActions) {
   <li>
      <button onclick=@(menuAction.Invoke())>
         @menuTitle
      </button> 
   </li>
   }
</div>

@code{

[Parameter]
public string Title {get; set;}

[Parameter]
public Dictionary<string, EventCallback> MenuActions {get; set;}

}

Totally lost, right now just getting this error:

error CS1503: Argument 2: cannot convert from 'method group' to 'EventCallback'

First off some good documentation on the topic:

It seems in your Child, you are not using the Blazor way to invoke an event, you are using HTML syntax, which would directly invoke JS code in the front end, oblivious to Blazor.

  <button onclick=@(menuAction.Invoke())>
     @menuTitle
  </button> 

Note: @onclick vs onclick mabye try:

  <button @onclick=MyMethod>
     @menuTitle
  </button> 
@code {
    void MyMethod() {
    //Invoke stuff here
    }
}

If you want to use JS-Interop read this .

Ofc you can load any JS code into the browser like with pure HTML and also write pure HTML to execute it, but with that you technically evade Blazor completely, like so:

onclick="console.log('Hello')"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM