How to obtain the target element on click event in Blazor

烈酒焚心 提交于 2020-02-03 11:02:09

问题


I want the exact target on which the click event has been triggered in ASP.NET Core blazor. Is this achievable?


回答1:


You can use @ref to get a reference to a DOM object, then pass it as a parameter to your handler function.

You can then pass it as a parameter to the JS Interop.

For example:

Counter.razor

@page "/counter"
@using Microsoft.JSInterop
@inject IJSRuntime JSRuntime

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<p>Last button clicked: @lastButtonClicked</p>

<button @ref=button1 class="btn btn-primary" @onclick="@(()=>IncrementCount(@button1))">Click me</button>
<button @ref=button2 class="btn btn-primary" @onclick="@(()=>IncrementCount(@button2))">Click me</button>


@code {

    private ElementReference button1;
    private ElementReference button2;

    private int currentCount = 0;
    private string lastButtonClicked = "None";

    private async void IncrementCount(ElementReference element)
    {
        currentCount++;
        await JSRuntime.InvokeVoidAsync("setElementText", element, "I was clicked");
    }
}

And make sure to add this script to Index.html

<script>
    window.setElementText = (element, text) => { console.log(element); element.innerText = text; }
</script>

Reference: https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interop?view=aspnetcore-3.1#detect-when-a-blazor-app-is-prerendering



来源:https://stackoverflow.com/questions/59213382/how-to-obtain-the-target-element-on-click-event-in-blazor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!