Blazor 组件怎么创建

来源:这里教程网 时间:2026-02-21 17:34:14 作者:

Blazor 组件通常以 .razor 文件形式存在,本质是带 HTML 模板和 C# 逻辑的混合文件,创建方式简单直接。

在 Visual Studio 或 VS Code 中新建 .razor 文件

右键项目(通常是 PagesComponents 或自定义文件夹)→ 选择“添加” → “新建项” → 找到“Razor 组件”模板(Visual Studio)或手动新建文本文件并命名为

MyComponent.razor
(VS Code)。确保扩展名是 .razor,不是 .cs 或 .html。

基础结构:@page + HTML + @code

一个最简 Blazor 组件至少包含三部分:

@page "/my-component" —— 可选,仅当需要作为页面路由时添加;组件复用时不加 纯 HTML 标记(支持 Razor 语法,如
@value
@if
@code { ... } 块 —— 放 C# 成员(字段、属性、方法)、生命周期方法(如
OnInitialized

示例:

<h3>Hello, @Name!</h3><br>@if (IsVisible)<br>{<br>    <p>Content is shown.</p><div class="aritcle_card flexRow">
                                                        <div class="artcardd flexRow">
                                                                <a class="aritcle_card_img" href="/xiazai/code/11102" title="极限网络办公Office Automation"><img
                                                                                src="https://www.herecours.com/d/file/efpub/2026/21-21/20260221140008179331.jpg" alt="极限网络办公Office Automation"  onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
                                                                <div class="aritcle_card_info flexColumn">
                                                                        <a href="/xiazai/code/11102" title="极限网络办公Office Automation">极限网络办公Office Automation</a>
                                                                        <p>专为中小型企业定制的网络办公软件,富有竞争力的十大特性:  1、独创 web服务器、数据库和应用程序全部自动傻瓜安装,建立企业信息中枢  只需3分钟。  2、客户机无需安装专用软件,使用浏览器即可实现全球办公。  3、集成Internet邮件管理组件,提供web方式的远程邮件服务。  4、集成语音会议组件,节省长途话费开支。  5、集成手机短信组件,重要信息可直接发送到员工手机。  6、集成网络硬</p>
                                                                </div>
                                                                <a href="/xiazai/code/11102" title="极限网络办公Office Automation" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
                                                        </div>
                                                </div><br>}<br><br>@code {<br>    private string Name = "Blazor";<br>    private bool IsVisible = true;<br>}

组件复用:通过标签名调用

保存为

Counter.razor
后,可在其他组件中像 HTML 标签一样使用:
<counter></counter>
。注意大小写敏感,且组件名需匹配文件名(首字母大写惯例)。若组件不在同一命名空间,需在父组件顶部加
@using YourApp.Components

可选但推荐:使用 @namespace 和 @inherits

在组件顶部加

@namespace MyApp.Components
明确命名空间;如需继承自自定义基类(比如封装通用状态),可用
@inherits MyBaseComponent
,前提是基类继承自
ComponentBase

基本上就这些 —— 不需要配置、不依赖额外命令,新建文件 + 写点 HTML 和 C#,就能跑起来。

相关推荐