如何在Blazor中不使用输入标签的情况下检测按键 [英] How to detect key press without using an input tag in Blazor

查看:539
本文介绍了如何在Blazor中不使用输入标签的情况下检测按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在Blazor中不使用HTML INPUT标记的情况下捕获键盘输入.按下键后,我将显示一个图形来表示所按下的字母.

I want to be able to capture keyboard input without using an HTML INPUT tag in Blazor. Once the key is pressed i will display a graphic to represent the letter pressed.

类似这样的东西

@page "/counter"
@using Microsoft.AspNetCore.Components.Web

<div @onkeypress="e => KeyPress(e)">
    Press any letter key
</div>

@code {

    private void KeyPress(KeyboardEventArgs e)
    {
        var letter = e.Key;
    }
}

当我在其上设置断点时,似乎没有调用KeyPress方法.任何帮助表示赞赏.

The KeyPress method does not appear to be called when I set a breakpoint on it. Any help much appreciated.

推荐答案

您快到了,但是您忘了将div放在焦点上.步骤如下:

You are almost there, but you forgot to make div focused. This is the steps:

0.-通过添加tabindex标记使div更具焦点:

0.- Make your div focusable adding tabindex tag:

<div 
    class="jumbotron"
    @onkeydown="@KeyDown"
    tabindex="0"
    @ref="myDiv" >
   <h1 class="display-4">
       @letter
   </h1>   
</div>

1.--例如,在_Host.cshtml上创建一个js代码以将焦点设置为div:

1.- Create a js code to set focus to your div, on _Host.cshtml for example:

    <script>
        window.SetFocusToElement = (element) => {
            element.focus();
        };
    </script>

此函数将元素引用作为参数.

This function takes an Element reference as the parameter.

2.-渲染组件后调用此函数.

2.- Call this function after your component is rendered.


protected ElementReference myDiv;  // set by the @ref attribute

protected async override Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender) 
    {
        await JSRuntime.InvokeVoidAsync("SetFocusToElement", myDiv);
    }            
}  

3.-实现自己的KeyDown:

protected void KeyDown(KeyboardEventArgs e)
{
    letter = $"Pressed: [{e.Key}]";
}

请注意,这不是Blazor问题,只是默认的html和js行为.我是通过写游戏学习它的,请在 Blagario 实验室中查看.

Notice that this is not a Blazor issue, is just the default html and js behavior. I learned it writing a game, check it out at Blagario lab.

运行:

演示在 Flappy Blazor Bird

编辑于2019年11月:

代码已通过 @Quango 改进(非常感谢)

Code improved by @Quango (many thanks)

这篇关于如何在Blazor中不使用输入标签的情况下检测按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆