如何在Blazor中执行客户端UI事件 [英] How to do client-side UI events in Blazor

查看:153
本文介绍了如何在Blazor中执行客户端UI事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始接触Blazor,我已经看到了这个新框架的巨大潜力.

I just started playing around with Blazor and I can already see the great potential of this new framework.

但是,我想知道它将如何处理简单的事情,例如将焦点放在输入控件上?例如,在处理click事件之后,我想将焦点设置为文本输入控件.我是否必须使用JQuery之类的东西,否则Blazor会为此类事情使用一些内置方法吗?

I'm wondering, though, how it will handle doing simple things like setting focus on an input control? For instance, after I handle a click event, I want to set the focus to a text input control. Do I have to use JQuery for something like that, or will Blazor have some built-in methods for that sort of thing?

谢谢

更新:我在下面发布了一个答案,并给出了一个示例,该示例如何通过从.Net代码中调用JavaScript函数来将焦点设置为控件.

从现在(Blazor 0.9.0)开始,您在Index.html中创建JavaScript函数(或从Index.html引用它们),然后在Blazor页面或组件中调用JsRuntime.InvokeAsync("functionName"), parms);

As of right now (Blazor 0.9.0) you create your JavaScript functions in the Index.html (or reference them from Index.html) and then in your Blazor page or component you call JsRuntime.InvokeAsync("functionName", parms);

https://docs.microsoft.com/zh-cn/aspnet/core/razor-components/javascript-interop

推荐答案

我想添加一个更新的示例(自0.9.0版本开始),该示例在某些情况下调用JavaScript函数将焦点设置到另一个控件上事件,例如单击按钮.对于刚开始使用Blazor的人(例如我)来说,这可能会有所帮助.

I want to add a more up-to-date (as of 0.9.0) example of calling a JavaScript function to set the focus to another control after some event, like clicking on a button. This might be helpful for someone just starting out with Blazor (like me).

此示例建立在 https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/build-your-first-razor- components-app?view = aspnetcore-3.0

首先,请按照文档中的所有说明进行操作.当您有待办事项列表页面时,请添加以下内容:

First, follow all the instructions in the documentation. When you have a working To-Do List page, then add the following:

  1. 在Index.html的底部,wwwroot下以及加载webassembly.js的脚本标签下方,添加以下脚本:

<script>
        window.MySetFocus = (ctrl) => {
            document.getElementById(ctrl).focus();
            return true;
        }
</script>

  1. 在todo.cshtml页面的顶部,添加以下using语句:

@inject IJSRuntime JsRuntime;

  1. 在todo.cshtml页面的@functions部分中,添加以下函数:

    async void Focus(string controlId)
    {
        var obj = JsRuntime.InvokeAsync<string>(
            "MySetFocus", controlId);
    }

  1. 在AddToDo()函数中,在将"newToDo"变量设置为空字符串的行的下面,添加对Focus函数的调用,并传入输入控件的字符串ID. (文档中的示例未将ID分配给输入控件,所以您自己添加一个即可.我将其命名为"todoItem".)


void AddTodo()
    {
        if (!string.IsNullOrWhiteSpace(newTodo))
        {
            todos.Add(new TodoItem { Title = newTodo });
            newTodo = string.Empty;
            Focus("todoItem"); // this is the new code
        }
    }

  1. 构建并运行您的应用.当您单击添加新项"按钮时,应将新项添加到列表中,将输入控件清空,并将焦点放回到输入控件中,以准备添加其他项.

这篇关于如何在Blazor中执行客户端UI事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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