是否可以使用父组件方法@onclick,或者我需要从子组件中调用它?
假设我想调用父方法 Foo()。
Parent
@page "/"
// Custom component button
<Button Text="Some text" @onclick="Foo" Apperance="@Style.secondary" />
@code {
async Task Foo()
{
// ...
}
}
Child
<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'.
我确实想要一个子按钮组件,当单击它时(在父组件中呈现) - 我想调用父组件中的方法。
所以我找到了我的问题的答案,你设计一个EventCallback
发现于docs https://learn.microsoft.com/en-us/aspnet/core/blazor/components/event-handling?view=aspnetcore-3.1#eventcallback.
所以对我来说,它看起来像这样。
Parent
@page "/"
// Custom component button
<Button Text="Some text" OnClickCallback="@Foo" Apperance="@Style.secondary" />
@code {
async Task Foo()
{
// ...
}
}
Child
<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
如果您想使用参数,请在文档中了解更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)