Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

c# - EventCallback vs Action not working in blazor

I'm trying to build a Proof of Concept with nested components.

I have a main-component which is declared the following

public abstract class VoidHtmlComponent : ComponentBase
{
    [Parameter] public EventCallback<MouseEventArgs> OnClick { get; set; }
}

and I pass an instance of e.g a TableHead to my Table component

<Shared.RazorComponents.Table TableHead="@(new TableHead{ OnClick = HandleTableHeadClick})" >
</Shared.RazorComponents.Table>

@code{
    private void HandleTableHeadClick(MouseEventArgs mouseEventArgs)
    {
        Trace.WriteLine($"TableHead has been clicked ...");
    }
}

This will not build stating

ClientPagesTable.razor(6,213): Error CS0428: Cannot convert method group 'HandleTableHeadClick' to non-delegate type 'EventCallback'. Did you intend to invoke the method?

I guess blazor is doing some magic here to convert the Action<MouseEventArgs> to an EventCallback<MouseEventArgs> but I am stuck at this point. I also changed the parameter to Action<MouseEventArgs> which throws an error on runtime saying the cast is invalid.

Already tried using EventCallbackFactory but got stuck there as well.

Using OnClick = new EventCallbackFactory().Create(this, HandleTableHeadClick) throws

Function statements require a function name

at runtime.

question from:https://stackoverflow.com/questions/65830448/eventcallback-vs-action-not-working-in-blazor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the issue is that you create an instance of the TableHead just like a property. Since we don't know anything about the Table component it self I just assume that the issue is is around there.

The markup for using Renderfragments for this case would like like something like this:

<Shared.RazorComponents.Table>
    <TableHead Context="context">
         <p>put what ever you want to render here. Like the nested component with event handler</p>
    </TableHead>
</Shared.RazorComponents.Table>

See the docs as a reference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...