我希望能够在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;
}
}
当我在其上设置断点时,似乎没有调用KeyPress方法。任何帮助,不胜感激。
您快到了,但是您忘了把div放在焦点上。这是步骤:
0.-使您的div可以添加tabindex
标签:
<div
class="jumbotron"
@onkeydown="@KeyDown"
tabindex="0"
@ref="myDiv" >
<h1 class="display-4">
@letter
</h1>
</div>
1.-创建一个js代码以将焦点设置到div,例如_Host.cshtml
:
<script>
window.SetFocusToElement = (element) => {
element.focus();
};
</script>
此函数将元素引用作为参数。
2.-渲染组件后调用此函数。
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实验室中查看。
运行中: