简体   繁体   English

"Blazor 将输入值绑定到 oninput 不适用于 onkeypress"

[英]Blazor binding input value to oninput not working with onkeypress

I am using blazor to do a search.我正在使用 blazor 进行搜索。 When I press a key in the input it checks if its an enter key and if it is then initiates the search.当我在输入中按下一个键时,它会检查它是否是输入键,如果是则启动搜索。 However, it appears that the value of the binded variable(keywordValue) does not update until i hit enter twice in a row.但是,绑定变量(keywordValue)的值似乎不会更新,直到我连续输入两次。 The first time if i press it the value is not updated.如果我第一次按下它,值不会更新。

<h1>Blogs</h1>
<fieldset>
    <label>Keyword Search</label>
    <input type="text" @bind="keywordValue" @bind:event="oninput" @onkeypress="KeywordEnterPressed"/>
    <button type="submit" @onclick="SearchBlogs">Search</button>
</fieldset>
private string keywordValue { get; set; }
protected async void KeywordEnterPressed(KeyboardEventArgs eventArgs)
    {
        if (eventArgs.Key == "Enter")
        {
            await SearchBlogs();
        }
    }

For example: If i type "test" into the input field and press enter it runs searchblogs() with a value of "".例如:如果我在输入字段中输入“test”并按下回车键,它将运行值为“”的 searchblogs()。 When i hit enter again then it runs searchblogs() with a value of "test" like it should.当我再次按 Enter 键时,它会运行 searchblogs(),其值为“test”,就像它应该的那样。

You should use Task instead of void您应该使用 Task 而不是 void

Write: protected async Task KeywordEnterPressed instead of protected async void KeywordEnterPressed写入: protected async Task KeywordEnterPressed而不是protected async void KeywordEnterPressed

Incidentaly, the type of the button element should be "button" instead of"submit"顺便说一下,按钮元素的类型应该是“button”而不是“submit”

Do this : <button type="button" @onclick="SearchBlogs"> instead of <button type="submit" @onclick="SearchBlogs">这样做: <button type="button" @onclick="SearchBlogs">而不是<button type="submit" @onclick="SearchBlogs">

Hope this helps...希望这可以帮助...

As per Nick's comment it appears to be the event ordering, binding not happened when key pressed event is run.根据尼克的评论,这似乎是事件排序,运行按键事件时未发生绑定。 I added a Task.Delay(100) to the key pressed event before the search to allow time for the binding and now behaving for me.我在搜索之前向按键事件添加了一个 Task.Delay(100),以便为绑定留出时间,现在对我来说。 Not great as the 100 is totally arbitary.不是很好,因为 100 是完全任意的。

由于事件排序,我通过使用“onkeyup”而不是“onkeypress”来实现它

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM