简体   繁体   中英

Blazor component event will not trigger

I am using an 'onKeyPress' event on a Blazor component and it will not trigger even though I am pressing a key.

<div class="row">
    <textarea id="test" class="form-control" @bind="text" @onkeypress="WordsLeft"></textarea>
    <p>Words left: @(MaxCount - CurrentWordCount)</p>
</div>

@code {
    [Parameter]
    public int MaxCount { get; set; }

    [Parameter]
    public string text { get; set; } = string.Empty;

    public int CurrentWordCount = 0;

    public void WordsLeft(KeyboardEventArgs e)
    {   
       ...
    }
}

Why isn't my WordsLeft method being called?

Have you add the <script src="_framework/blazor.server.js"/> to the .cshtml file? This needs to be placed after the component that declares the events. and also make sure to add _Imports.razor file into your Components folder with the following using statements.

@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop

(Sorry can't comment yet but) For me it does call the WordsLeft function. Have you tried to debug and step through? I also have other thoughts to improve code if you need more help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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