Blazor输入上的PreventDefault [英] PreventDefault on Blazor input

查看:105
本文介绍了Blazor输入上的PreventDefault的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有输入字段的简单应用程序,应在键入时插入预定义的文本.

I have a simple application with an input field that should insert a predefined piece of text as you type.

我的代码如下:

<input type="text" bind="@PetitionInput" onkeydown="@PetitionHandleKeyDown" />
@functions
{
    private int _petitionCharStep = 0;
    private string _petition = "This is a dummy text";
    public string PetitionInput { get; set; } = string.Empty;

    void PetitionHandleKeyDown(UIKeyboardEventArgs arg) {
        PetitionInput += _petition[_petitionCharStep];
        _petitionCharStep++;

        Console.WriteLine(PetitionInput);
    }
}

当输入字段具有焦点时,当我在键盘上按一个字母时,则应该将字符串_petition中的第一个字母添加到输入中.当我按键盘上的任何字母时,它应该在输入字段中输入第二个字母.依此类推.

When the input field has focus, and I press a letter on my keyboard, then it should add the first letter from the string _petition to the input. When I press any letter on my keyboard, it should enter the second letter into the input field. And so on.

我遇到的问题是,它还在我按键盘输入的末尾添加了字母.我想防止发生这种情况.

The problem I have is that it also adds the letter at the end of the input that I pressed on my keyboard. I want to prevent that from happening.

是否有一种方法可以仅使用问题Blazor代码来解决此问题?

Is there a way to fix this using issue Blazor code only?

我有一个在线演示此处.

推荐答案

在Blazor中您可能会有所不同.

You can think a little differently in Blazor.

您可以设置值"并处理"oninput"事件,而不是使用"bind"和防止按键操作,例如:

Rather than using "bind" and preventing the keystroke, you can set the "value" and handle the "oninput" event, like this:

https://blazorfiddle.com/s/azdn892n

@page "/"
<h1>Start typing something...</h1>
<input type="text" value="@PetitionInput" oninput="@PetitionHandleKeyDown" />

@functions {
    private int _petitionCharStep = 0;
    private string _petition = "This is a dummy text";
    public string PetitionInput { get; set; } = string.Empty;

    void PetitionHandleKeyDown(UIChangeEventArgs arg) {
        PetitionInput = _petition.Substring(0,++_petitionCharStep);
        Console.WriteLine(PetitionInput);
    }
}

我无法想象您为什么要这样做,而且还需要做很多额外的事情来覆盖退格键,箭头键,制表符等...

I can't imagine why you would want to do this, and there are many extra things you need to do to cover backspaces, arrow keys, tab etc...

这篇关于Blazor输入上的PreventDefault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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