首页 > 解决方案 > Razor 组件标签助手实际上并未加载 razor 组件

问题描述

我一直按照本指南中的步骤在我的 Razor 应用程序中设置 Blazor 组件。我完成了该指南“准备应用程序”部分的所有步骤,修改了 _Layout.cshtml 和 Startup.cs 文件并添加了 _Imports.razor 文件。为了测试这一点,我只是想实现一个基本的计数器组件。

我将以下代码添加到 MyApp/Components/Counter.razor:

<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    [Parameter]
    public int InitialValue { get; set; }

    private void IncrementCount() => currentCount++;

    protected override void OnParametersSet()
    {
        currentCount = InitialValue;
    }
}

然后在 MyApp/Pages/Counter.cshtml 我有这个:

@page
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Web
@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.JSInterop
@using MyApp
@using MyApp.Components

//This does not work--it appears exactly like this in the HTML when the page loads
<component type="typeof(Counter)" render-mode="ServerPrerendered" />

//this works as expected and loads the razor component
@(await Html.RenderComponentAsync<Counter>(RenderMode.ServerPrerendered))

请注意,我从 _Imports.razor 文件中复制了所有 using 指令,以查看是否修复了问题,但这并没有什么不同。我的理解是 RenderComponentAsync 函数已经过时,“组件”标签助手是当前使用剃须刀组件的方式。我也更喜欢使用这种语法,因为它更容易传递参数。有谁知道我缺少什么才能让它工作?

标签: razorblazor

解决方案


哎呀,在搞砸了几个小时后,我意识到我的应用程序在 Net Core 3.0 上,并且标签助手仅在 3.1+ 中可用。将 MyApp.csproj 更新为 3.1 来修复它:

<TargetFramework>netcoreapp3.1</TargetFramework> 

推荐阅读