将方法传递给组件 [英] Passing method to component
问题描述
我一直在尝试找出可能的方法以及如何将方法从主页传递到 Blazor 中的组件中.
I have been trying to work out how if its possible and how to pass a method from the main page into a component in Blazor.
我有一个简单的剃刀页面,其中包含一个带有按钮的组件.我想将剃刀页面的 onclick 方法传递给组件中的按钮
I have a simple razor page, which contains a component with a button. I want to pass the onclick method from the razor page to the button in the component
注意:我不需要这个方法来返回任何无效的东西.我只需要能够在组件上的按钮中从主页调用方法.我只是在这里添加 int 作为猜测,因为它在抱怨 T
Note: I do not need this method to return anything void is fine. I just need to be able to call a method from the main page in a button on the component. I only added int here as a guess since it was complaining about 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 {
}
错误
上面的代码给了我以下错误
Errors
The above code gives me the following error
btnClick"没有重载匹配委托Action"
Gives me No overload for 'btnClick' matches delegate 'Action'
我也尝试过类型 T 并且失败了,因为 Blazor 由于某种原因无法找到类型 T 的引用
I tried doing type T as well and that failed as Blazor cant for some reason find the reference for type T
从答案中拼凑出来的工作示例.PassingMethodToComponent
Working example pieced together from the answers. PassingMethodToComponent
推荐答案
下面是一个将方法从父级传递给子级并由子级调用它的示例.由于您不需要返回值,我只是使用 Action
而不是 Action
.
Here is an example of passing a method from a parent to a child and the child invoking it. As you don't require a return value I'm just using Action
rather than Action<T>
.
有很多方法可以让这段代码更紧凑,但我已经找了一个更详细的例子,希望能更好地展示正在发生的事情.
There are many ways you can make this code more compact, but I've gone for a more verbose example to hopefully show what's happening a bit better.
父组件:
@page "/"
<h1>Hello, world!</h1>
Welcome to your new app.
<Child ParentMethod="@SayHello" />
@code {
private void SayHello()
{
Console.WriteLine("Hello!");
}
}
子组件:
<h3>Child</h3>
<button @onclick="@InvokeParentMethod">Click Me!</button>
@code {
[Parameter] public Action ParentMethod { get; set; }
private void InvokeParentMethod()
{
ParentMethod?.Invoke();
}
}
这篇关于将方法传递给组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!