【发布时间】:2019-11-11 20:24:24
【问题描述】:
我一直在尝试找出可行的方法以及如何将方法从主页传递到 Blazor 中的组件。
我有一个简单的剃须刀页面,其中包含一个带有按钮的组件。我想将剃须刀页面中的onclick方法传递给组件中的按钮
注意:我不需要这个方法来返回任何 void 就可以了。我只需要能够从组件上的按钮中的主页调用方法。我只是在这里添加了 int 作为猜测,因为它在抱怨 T
页面
@page "/test"
@using Testing.Client.Model;
@using System.Threading;
<TestMethodPassing ExternalMethod="@btnClick"></TestMethodPassing>
@code {
public Action<int> btnClick(){ return 1;}
}
组件模型
public class TestingMethodPassingModel : ComponentBase
{
[Parameter]
protected Action<int> ExternalMethod { get; set; }
}
组件
@inherits TestingMethodPassingModel;
@using testing.Client.Model;
@using System.Threading;
<button class="btn btn-primary" @onclick="@ExternalMethod" autofocus>External button</button>
@code {
}
错误
上面的代码给了我以下错误
“btnClick”与委托“Action”没有重载
我也尝试过使用 T 类型,但由于 Blazor 出于某种原因无法找到类型 T 的引用而失败了
更新说明
从答案拼凑而成的工作示例。 PassingMethodToComponent
【问题讨论】:
-
我不太了解 razor,但我很确定 onclick-delegate 不会期望 int-argument。
-
我已经创建了您的示例,它给出了
CS1503 Argument 2: cannot convert from 'System.Action<int>' to 'Microsoft.AspNetCore.Components.EventCallback错误。还有CS0428 Cannot convert method group 'btnClick' to non-delegate type 'object'. Did you intend to invoke the method?. -
您的代码并未真正显示您希望如何/在何处使用返回值。
-
同样
return 1;也不会编译 -CS0029 Cannot implicitly convert type 'int' to 'System.Action<int>'。 -
此时我并没有真正参加任何活动,我一直在努力让它发挥作用。我真的不需要该方法来返回任何我只需要能够通过它的东西。 Gitter 上的某个人说要使用 T,但它没有用,所以我抓住了稻草,假设它需要一个 return var。您的右键 Onclick 不需要返回 var