如何使用VS 2019创建Blazor组件背后的代码?

rab*_*ens 1 blazor

我可以创建一个内联组件

<h1>@foo</h1>

@functions {

    string foo = "foo";
}
Run Code Online (Sandbox Code Playgroud)

但是,当我创建Foo.razor只包含:

<h1>@foo</h1>
Run Code Online (Sandbox Code Playgroud)

Foo.razor.cs包含:

namespace MyApp.Client.Components {
    public class Foo: ComponentBase {

        public string foo;
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到:

Error   CS0101  The namespace 'MyApp.Client.Components' already contains a definition for 'Foo'
Run Code Online (Sandbox Code Playgroud)

我正在使用最新的VS 2019和Blazor库。

我究竟做错了什么?

Kne*_*lis 12

自 2019 年 10 月起,可以使用部分类。所以今天你可以像这样在代码隐藏文件中命名类:

public partial class Foo : ComponentBase
{
    protected override Task OnInitializedAsync()
    {
        // do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您命名类文件Foo.razor.cs,它将出现Foo.razor在解决方案资源管理器中的razor 文件下。


snr*_*snr 8

我不喜欢用文字来解释方法,而是喜欢形象化。

在此输入图像描述


JOS*_*Ftw 5

当前,“代码隐藏”和.razor视图不能共享相同的名称。

因此,当您拥有时Foo.razor.csFoo.razor它将被视为同一文件,从而导致冲突。

目前的解决方法:将您的重命名Foo.razor.csFooBase.cs(或其他)。

然后在中Foo.razor,添加@inherits FooBase

这里有一个与此相关的GitHub问题:https : //github.com/aspnet/AspNetCore/issues/5487


M.H*_*san 5

在使用实验性 Razor 的 Vs2019 v 16.8.4 中,一个新选项“将块提取到代码后面”

步骤是:

  • 启用expermintal Razor:选项->环境->预览功能->启用expermintal Razor编辑器(需要重启)
  • 将光标放在 @{code} 上或按 Control + 。//点
  • 下拉菜单显示“将块提取到代码隐藏”
  • 单击“将块提取到代码隐藏”
  • 然后,Vs2019 将代码提取到并行创建的新 *.razor.cs 文件中,例如 counter.razor 组件的“Counter.razor.cs”。

生成的类样本:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Lab2.Pages
{
    public partial class Counter
    {
        private int currentCount = 0;

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

Run Code Online (Sandbox Code Playgroud)

注意:生成的分部类不会继承 ComponentBase,因此需要解决。