我刚刚开始玩Blazor,我已经看到了这个新框架的巨大潜力。
但是,我想知道它将如何处理一些简单的事情,比如将焦点放在一个输入控件上?例如,在处理click事件后,我希望将焦点设置为文本输入控件。我需要用JQuery来做类似的事情吗,还是Blazor会有一些内置的方法来处理这类事情呢?
谢谢
更新:我在下面发布了一个答案,并举例说明了如何通过从.Net代码调用JavaScript函数将焦点设置到控件上。
现在(Bazor0.9.0),您在JavaScript中创建Index.html函数(或从Index.html中引用它们),然后在Blazor页面或组件中调用JsRuntime.InvokeAsync("functionName",parms);
https://learn.microsoft.com/en-us/aspnet/core/razor-components/javascript-interop
发布于 2019-03-13 00:50:40
我想添加一个最新的(截至0.9.0)的例子,调用一个JavaScript函数,在某些事件之后将焦点设置为另一个控件,比如单击按钮。这可能对刚开始使用Blazor的人有帮助(比如我)。
此示例构建在https://learn.microsoft.com/en-us/aspnet/core/tutorials/build-your-first-razor-components-app?view=aspnetcore-3.0上的Blazor文档“构建第一个Blazor组件应用程序”中的示例代码之上。
首先,遵循文档中的所有说明。当您有工作待办事项列表页时,然后添加以下内容:
<script>
window.MySetFocus = (ctrl) => {
document.getElementById(ctrl).focus();
return true;
}
</script>@inject IJSRuntime JsRuntime; async void Focus(string controlId)
{
var obj = JsRuntime.InvokeAsync<string>(
"MySetFocus", controlId);
}void AddTodo()
{
if (!string.IsNullOrWhiteSpace(newTodo))
{
todos.Add(new TodoItem { Title = newTodo });
newTodo = string.Empty;
Focus("todoItem"); // this is the new code
}
}发布于 2018-03-24 09:29:59
Blazor只是JavaScript的替代品(更准确地说,是“增值”)。它是客户端唯一的解决方案(但将来可能会为ASP.NET添加一些简单的绑定)。
不过,它完全基于HTML和CSS。C#正在使用web程序集替换JS部件。因此,访问/修改HTML控件的方式没有任何改变。
到目前为止(版本为0.1.0),您必须依赖HTML focus()方法来完成您想要做的事情(是的,您现在必须使用JavaScript :( ) )。
// Not tested code
// This is JavaScript.
// Put this inside the index.html. Just below <script type="blazor-boot"></script>
<script>
Blazor.registerFunction('Focus', (controlId) => {
return document.getElementById(controlId).focus();
});
</script>
//and then wrap it for calls from .NET:
// This is C#
public static object Focus(string controlId)
{
return RegisteredFunction.Invoke<object>("Focus", controlId);
//object type is used since Invoke does not have a overload for void methods. Don't know why.
//this will return undefined according to js specs
}有关更多信息,请参考下面的内容。
如果您想要改进JS的包装整洁的,您可以这样做:https://stackoverflow.com/a/49521216/476609
public class BlazorExtensionScripts : Microsoft.AspNetCore.Blazor.Components.BlazorComponent
{
protected override void BuildRenderTree(Microsoft.AspNetCore.Blazor.RenderTree.RenderTreeBuilder builder)
{
builder.OpenElement(0, "script");
builder.AddContent(1, "Blazor.registerFunction('Focus', (controlId) => { document.getElementById(controlId).focus(); });");
builder.CloseElement();
}
public static void Focus(string controlId)
{
RegisteredFunction.Invoke<object>("Focus", controlId);
}
}然后将此组件添加到根:(App.cshtml):
<BlazorExtensionScripts></BlazorExtensionScripts>
<Router AppAssembly=typeof(Program).Assembly />发布于 2020-08-26 23:19:04
来自.NET 5预览8
Blazor现在在ElementReference上有了一个ElementReference方便的方法来设置该元素的UI焦点。
<button @onclick="() => textInput.FocusAsync()">Set focus</button>
<input @ref="textInput"/>https://stackoverflow.com/questions/49460516
复制相似问题