gpt4 book ai didi

c# - 将方法传递给组件

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:03 26 4
gpt4 key购买 nike

我一直在尝试弄清楚如何将方法从主页传递到 Blazor 中的组件。

我有一个简单的剃​​须刀页面,其中包含一个带按钮的组件。我想将 onclick 方法从 razor 页面传递到组件中的按钮

注意:我不需要此方法返回任何 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 {


}

错误

上面的代码给我以下错误

Gives me No overload for 'btnClick' matches delegate 'Action'

我也尝试过类型 T 但失败了,因为 Blazor 出于某种原因无法找到类型 T 的引用

更新说明

根据答案拼凑的工作示例。 PassingMethodToComponent

最佳答案

这是一个将方法从父级传递给子级并由子级调用的示例。由于您不需要返回值,我只是使用 Action而不是 Action<T> .

有很多方法可以让这段代码更紧凑,但我已经找到了一个更详细的例子,希望能更好地展示正在发生的事情。

父组件:

@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();
}

}

关于c# - 将方法传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56831266/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com