如何在Blazor中不使用输入标签的情况下检测按键

Mar*_*son 2 keyboard input blazor

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

像这样

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我在其上设置断点时,似乎没有调用KeyPress方法。任何帮助,不胜感激。

小智 26

如果还有人想要解决方案。我认为现在在 .NET 5 中,您可以在 Blazor 中实现此目的,而无需使用 js。设置焦点和 tabindex 很重要,当您失去焦点或将焦点设置到另一个元素时,这将不起作用。这对我有用:

    <table @ref="testRef" tabindex="0" @onkeydown="HandleKeyDown">
    <thead>
        <tr>
            <th>
                Pressed Key
            </th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                @pressedKey
            </td>
        </tr>
    </tbody>
    </table>

    private ElementReference testRef;
    private string pressedKey;
    
    private void HandleKeyDown(KeyboardEventArgs e)
    {
        pressedKey = e.Key;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await testRef.FocusAsync();
        }
    }
Run Code Online (Sandbox Code Playgroud)


dan*_*era 5

您快到了,但是您忘了关注div。步骤如下:

0.-使您的div可聚焦添加tabindex标签:

<div 
    class="jumbotron"
    @onkeydown="@KeyDown"
    tabindex="0"
    @ref="myDiv" >
   <h1 class="display-4">
       @letter
   </h1>   
</div>
Run Code Online (Sandbox Code Playgroud)

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

    <script>
        window.SetFocusToElement = (element) => {
            element.focus();
        };
    </script>
Run Code Online (Sandbox Code Playgroud)

该函数将元素引用作为参数。

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


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

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

3.-实现自己的KeyDown

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

请注意,这不是Blazor问题,只是默认的html和js行为。我是在写游戏的过程中学习的,并在Blagario实验室进行了检查。

运行:

蓬松的火烈鸟鸟

Flappy Blazor Bird的演示

编辑于2019年11月:

@Quango改进了代码(非常感谢)