【发布时间】:2021-06-26 05:11:53
【问题描述】:
我正在尝试将我的 Blazor Server 项目拆分为组件,以使其更易于管理。
我希望我的组件有一个作为参数传入的函数。该函数接受一个字符串参数,并在单击按钮时使用与组件不同的名称调用它。
我尝试了一些我在网上找到的答案,但它们似乎不起作用(比如绑定事件)
代码
我有一个名为 ItemMenu.razor 的组件和我的索引页 Index.razor。
ItemMenu.razor:
<button @onclick="() => OnClickFunction.Invoke(foo)">foo</button>
<button @onclick="() => OnClickFunction.Invoke(ping)">ping</button>
@code {
[Parameter] public Action<string> OnClickFunction { get; set; }
const string foo = "bar";
const string ping = "pong";
}
Index.razor:
@page "/"
<h1>This is my index page!</h1>
<ItemMenu OnClickFunction="ShowName" /> @*Error: No overload for 'ShowName' matches delegate 'Action'*@
@code {
public void ShowName(string myName)
{
Console.WriteLine(myName);
}
}
错误
Index.html 中的第 3 行抛出错误 No overload for 'ShowName' matches delegate 'Action'
解决方案
原来我只需要将变量重命名为 OnClick 而不是 OnClickFunction...
好的@enet 指出变量名不是问题。 在 blazor 中,我们应该使用 EventCallback 而不是 Action。
在我的案例中,真正的问题是 Visual Studio,因为我之前在查看其他答案时发现了这个解决方案。 VS 决定在这一行显示错误,即使它编译并运行良好...
【问题讨论】:
-
这能回答你的问题吗? Passing method to component
标签: c# blazor blazor-server-side blazor-component