我刚开始玩Blazor,我已经看到了这个新框架的巨大潜力。
不过,我想知道如何处理简单的事情,例如将注意力集中在输入控件上?例如,在我处理click事件后,我想将焦点设置为文本输入控件。我是否必须使用JQuery这样的东西,还是Blazor会为这类东西提供一些内置的方法?
谢谢
更新:这是我现在这样做的方式,直到我了解更多关于Blazor的信息。 (这很有效,但我知道当Blazor准备好迎接黄金时段时,会有更好的方法来处理这样的事情。)
在我看来,我有以下脚本部分:
<script>
Blazor.registerFunction('FocusControl', (ctrl) => {
document.getElementById(ctrl).focus();
return true;
});
</script>
然后,在函数部分我有这个功能:
private void FocusControl(string ctrl)
{
RegisteredFunction.Invoke<bool>("FocusControl", ctrl);
}
然后我从Refresh方法中调用它。 (这是使用TalkingDotNet提供的示例代码,网址为http://www.talkingdotnet.com/create-a-crud-app-using-blazor-and-asp-net-core/ )
private async Task Refresh()
{
todos = await Http.GetJsonAsync<ToDoList[]>("/api/ToDo");
FocusControl("todoName");
StateHasChanged();
}
Blazor只是javascript的替代品(更准确地说是“增值”)。它只是一个客户端解决方案(但未来可能会与ASP.Net轻松绑定)。
它完全基于html和CSS。 C#正在使用Web程序集替换js部分。因此,访问/修改html控件的方式没有任何改变。
截至目前(版本0.1.0),你必须依靠HTML DOM 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 undifined according to js specs
}
有关更多信息,请参阅下文。
如果你想整齐地改善js的pakaging 。你可以做这样的事情。 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 />
你不能直接调用JavaScript函数。您需要先注册您的功能,如,
<script>
Blazor.registerFunction('ShowControl', (item) => {
var txtInput = document.getElementById("txtValue");
txtInput.style.display = "";
txtInput.value = item;
txtInput.focus();
});
return true;
</script>
然后你需要在C#中声明一个调用这个JavaScript函数的方法。喜欢,
private void CallJavaScript()
{
RegisteredFunction.Invoke<bool>("ShowControl", itemName);
}
您可以通过单击按钮调用此C#方法。喜欢,
<button id="btnShow" class="btn btn-primary" @onclick(CallJavaScript)>Show</button>
这篇文章使用Blazor和ASP.NET Core创建一个CRUD应用程序显示了一个从Blazor调用JavaScript的工作演示。