How to set the focus to an InputText element?

前端 未结 5 502
灰色年华
灰色年华 2021-01-12 17:21

Using the example from the Microsoft docs, I\'m trying to programmatically set the focus to an input element.

Unfortunately, the example uses a standard

5条回答
  •  一向
    一向 (楼主)
    2021-01-12 18:03

    I was able to accomplish this by entering the JavaScript directly in the Host.chtml file (you can also add a .js file like the walkthrough suggests):

    
    

    Next, in an extension file, I've added the extension (NOTE: I renamed Focus to FocusAsync because of naming standards:

    public static async Task FocusAsync(this ElementReference elementRef, IJSRuntime jsRuntime)
    {
        await jsRuntime.InvokeVoidAsync(
            "exampleJsFunctions.focusElement", elementRef);
    }
    

    Then in the razor page (or component), inject the IJSRuntime, Add an ElementReference and tie it to the element you want to focus (Note: Method names were changed to abide to naming standards):

    @inject IJSRuntime JSRuntime
    @using JsInteropClasses
    
    
    
    
    @code {
        private ElementReference username;
    
        public async Task SetFocusAsync()
        {
            await username.FocusAsync(JSRuntime);
        }
    }
    

提交回复
热议问题