将Blazor代码移至代码后 - 简单的例子

问题描述 投票:0回答:1

我刚刚开始学习Blazor教程,并试图掌握代码。 我有一个剃刀页面,看起来像这样(来自教程)。

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

<!--
    This has been moved to the code-behind.
@code {
    private int currentCount = 0;

    private void IncrementCount() {
        currentCount++;
    }
}
-->

后面的代码给了我几个错误 说Counter已经被定义了 而且IncrementCount已经存在。 我后面的代码是这样的。

using Microsoft.AspNetCore.Components;

namespace BlazorApp8.Pages {

    public partial class CounterCode : ComponentBase {

        protected int currentCount = 0;

        protected void IncrementCount () {
            currentCount++;
        }


    }

}

我知道我做错了一些简单的事情,但不确定是什么。 谁能帮帮我?

blazor code-behind
1个回答
0
投票

我明白了。 在你的客户端代码中,你必须继承你的类,像这样。

@inherits CounterCode   <!-- This is what I missed -->
@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

0
投票

我更喜欢用另一种方式来创建一个代码文件。

在同一目录内新建一个类文件Counter.razor.cs。在类中添加局部。Done!

© www.soinside.com 2019 - 2024. All rights reserved.