作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我制作了一个带有事件的组件,如 docs 中所述。
如果我使用该组件的多个实例,有什么方法可以判断是哪个实例触发了事件?
在“常规”.net 中通常有一个 sender
范围。
看我的 BlazorFiddle
...或在这里查看我的示例代码:
子组件
<div class="panel panel-default">
<div class="panel-heading">@Title</div>
<div class="panel-body">@ChildContent</div>
<button class="btn btn-primary" @onclick="OnClick">
Trigger a Parent component method
</button>
</div>
@code {
[Parameter]
private string Title { get; set; }
[Parameter]
private RenderFragment ChildContent { get; set; }
[Parameter]
private EventCallback<UIMouseEventArgs> OnClick { get; set; }
}
@page "/"
<ChildComponent Title="Panel Title from Parent"
OnClick="@ShowMessage">Hello child 1</ChildComponent>
<br>
<br>
<ChildComponent Title="Panel Title from Parent"
OnClick="@ShowMessage">Hello child 2</ChildComponent>
<br>
<br>
<p><b>@messageText</b></p>
@code {
private string messageText;
private void ShowMessage(UIMouseEventArgs e)
{
// How do I get which ChildComponent was the sender?
messageText = DateTime.Now.ToString() + ": Message from child ?"
}
}
最佳答案
不幸的是,您没有发件人,这里已经讨论过这个话题:https://github.com/aspnet/Blazor/issues/1277 .
No. That would involve creating some new way to track the identity of a DOM element.
If you were able to describe at a more high level what sort of functionality you're trying to implement, it might be there's a more idiomatically Blazor-ish way to achieve what you want simply.
ShowMessage
方法。
@page "/"
<ChildComponent Title="Panel Title from Parent"
OnClick="@((ev) => ShowMessage(ev, 1))">Hello child 1</ChildComponent>
<br>
<br>
<ChildComponent Title="Panel Title from Parent"
OnClick="@((ev) => ShowMessage(ev, 2))">Hello child 2</ChildComponent>
<br>
<br>
<p><b>@messageText</b></p>
@code {
private string messageText;
// ex: Blazor 0.7 (Old)
private void ShowMessage(UIMouseEventArgs e, int childId)
{
// How do I get which ChildComponent was the sender?
messageText = DateTime.Now.ToString() + ": Message from child " + childId.ToString();
}
// ex: .NET Core 3.0 (Updated)
// UIMouseEventsArgs were removed
// Replace Microsoft.AspNetCore.Components.UIEventArgs with System.EventArgs and remove the “UI” prefix from all EventArgs derived types (UIChangeEventArgs -> ChangeEventArgs, etc.).
// https://devblogs.microsoft.com/aspnet/asp-net-core-and-blazor-updates-in-net-core-3-0-preview-9/
private void ShowMessage(MouseEventArgs e, int childId)
{
// How do I get which ChildComponent was the sender?
messageText = DateTime.Now.ToString() + ": Message from child " + childId.ToString();
}
}
关于asp.net-core - Blazor:如何从子组件中的事件中获取发送者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57395108/
我是一名优秀的程序员,十分优秀!