使用LazyAssemblyLoader加载的Razor类库中NavLink无法使用
问题场景
在通过LazyAssemblyLoader加载的Razor类库组件中使用NavLink标记时,出现以下错误:
发现名称为'NavLink'的意外标记元素。如果这是组件,请添加其命名空间的@using指令。
使用的NavLink代码如下:
<NavLink class="nav-link" href="@item.Name" Match="NavLinkMatch.All"> <span class="oi @item.Name" aria-hidden="true"></span> @item.Name </NavLink>
对应的App.razor代码:
@using System.Reflection @using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.WebAssembly.Services @using Microsoft.Extensions.Logging @inject LazyAssemblyLoader AssemblyLoader @inject ILogger<App> Logger @inject HttpClient Http <ErrorBoundary> <ChildContent> <Router AppAssembly="@typeof(App).Assembly" AdditionalAssemblies="@LazyLoadedAssemblies" OnNavigateAsync="@OnNavigateAsync"> <Found Context="routeData"> <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /> <FocusOnNavigate RouteData="@routeData" Selector="h1" /> </Found> <NotFound> <PageTitle>Not found</PageTitle> <LayoutView Layout="@typeof(MainLayout)"> <p role="alert">Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router> </ChildContent> <ErrorContent Context="errorException"> <div class="blazor-error-boundary"> @{ OnError(@errorException); } @*calls custom handler*@ @if (Utilities.IsDebug) { <p>@errorException.ToString()</p> @*prints exeption on page*@ } else { <p>@(errorException.Message.AsNullIfEmpty() ?? errorException.GetType().FullName)</p> @*prints exeption on page*@ } </div>> </ErrorContent> </ErrorBoundary> @code { private List<Assembly> LazyLoadedAssemblies = new List<Assembly>(); private async Task OnNavigateAsync(NavigationContext args) { try { if (args.Path == "" || args.Path == "menu1" || args.Path == "menu2") { IEnumerable<Assembly> assemblies = await AssemblyLoader.LoadAssembliesAsync(new[] { "MyProject.Test.dll" }); LazyLoadedAssemblies.AddRange(assemblies); } } catch (Exception ex) { Logger.LogError("Error: {Message}", ex.Message); } } protected override void OnInitialized() { // UIEngine.Initialize(); ComponentsService.Initialize(Http); base.OnInitialized(); } public void OnError(Exception exception) { } }
解决方法
方法1:在单个组件中添加命名空间引用
在使用NavLink的Razor组件顶部添加命名空间指令:
@using Microsoft.AspNetCore.Components.Routing
方法2:全局添加命名空间引用(推荐)
在Razor类库的_Imports.razor文件中添加该命名空间,类库内所有组件将自动识别NavLink:
@using Microsoft.AspNetCore.Components.Routing
原因说明
NavLink组件隶属于Microsoft.AspNetCore.Components.Routing命名空间,懒加载的Razor类库不会默认引入该命名空间,必须手动添加引用才能让编译器识别组件。
内容的提问来源于stack exchange,提问作者Asier Cayón Francisco
相关产品推荐
相关产品推荐

