Blazor按钮,使用父组件@onclick [英] Blazor button, use parent component @onclick
问题描述
是否可以使用父组件方法@onclick,还是需要从子对象中调用它?
Is it possible to use the parent component method @onclick, or do I need to invoke it from the child?
假设我要调用父方法Foo().
Let's say I want to invoke parent method Foo().
父母
@page "/"
// Custom component button
<Button Text="Some text" @onclick="Foo" Apperance="@Style.secondary" />
@code {
async Task Foo()
{
// ...
}
}
孩子
<button class="btn @_cssClass"><span>@Text</span></button>
@code {
public enum Style
{
primary,
secondary,
tertiary,
danger
}
[Parameter]
public string Text { get; set; }
[Parameter]
public Style Apperance { get; set; }
private string _cssClass { get; set; }
protected override void OnInitialized()
{
_cssClass = Apperance switch
{
Style.secondary => "btn--secondary",
Style.tertiary => "btn--tertiary",
Style.danger => "btn--danger",
_ => "btn--primary"
};
}
}
我收到此错误:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Object of type 'Tidrapport.Client.Components.Button' does not have a property matching the name 'onclick'.
System.InvalidOperationException: Object of type 'Tidrapport.Client.Components.Button' does not have a property matching the name 'onclick'.
我确实想要一个子按钮组件,并且单击它(在父对象中呈现)时-我想在父组件中调用一个方法.
I do want a child-button component, and when it's clicked (rendered in parent) - I want to invoke a method in the parent component.
推荐答案
所以我找到了我的问题的答案,您设计了在
So I've found the answer to my question, you design an EventCallback
found in the docs.
所以对我来说,看起来像这样.
So for me, it looks like this.
父母
@page "/"
// Custom component button
<Button Text="Some text" OnClickCallback="@Foo" Apperance="@Style.secondary" />
@code {
async Task Foo()
{
// ...
}
}
孩子
<button class="btn @_cssClass" @onclick="OnClickCallback"><span>@Text</span></button>
@code {
public enum Style
{
primary,
secondary,
tertiary,
danger
}
[Parameter]
public string Text { get; set; }
[Parameter]
public Style Apperance { get; set; }
private string _cssClass { get; set; }
[Parameter]
public EventCallback OnClickCallback { get; set; } // this is where to you pass the parent function to be executed as a callback
protected override void OnInitialized()
{
_cssClass = Apperance switch
{
Style.secondary => "btn--secondary",
Style.tertiary => "btn--tertiary",
Style.danger => "btn--danger",
_ => ""
};
}
}
因此onclick事件绑定到您在子组件中设计的事件处理程序.如果要使用参数,可以为 T
类型,有关更多信息,请参见文档.
So the onclick event is bound to the eventhandler you design in the child component. It can be of type T
if you want to use arguments, more on that in the docs.
这篇关于Blazor按钮,使用父组件@onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!