简体   繁体   English

Blazor创建共享组件库

[英]Blazor create shared component library

I am trying to work out how to create a shared component library in Blazor. 我正在尝试找出如何在Blazor中创建共享组件库的方法。 Basically i want to create my components once and then be able to use them in multiple UI projects. 基本上,我想一次创建我的组件,然后能够在多个UI项目中使用它们。

Component library 组件库

I created a simple component library as follows 我创建了一个简单的组件库,如下所示

dotnet new blazorlib -n UsComponentLibrary.Lib

Created a component component1.razor 创建了一个组件component1.razor

<h3>Component1 from lib</h3>

@code {

}

UI UI

I added a reference to the library in the ui project. 我在ui项目中添加了对该库的引用。 edited the _host.chtml file to include it 编辑了_host.chtml文件以包含它

@page "/"
@namespace UsComponentLibrary.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, UsComponentLibrary.Lib

Added it to one of the pages 将其添加到页面之一

@page "/counter"

hello

<Component1></Component1>

@code {


}

output 产量

The only thing its displaying is Hello i am not getting the text from the component in the library. 它唯一显示的是Hello,我不是从库中的组件获取文本。 What am i missing? 我想念什么? Its like the ui page can see the component but when I run it its not there. 就像ui页面一样,它可以看到该组件,但是当我运行它时,它不存在。

You need to import the namespaces from your library project with using statements not the addTagHelper . 您需要using而不是addTagHelper语句从库项目中导入名称空间。 This was a change that came in with Preview 4. 这是预览版4带来的更改。

I would suggest you edit the root _Imports.razor file in your UI project and add the namespaces there. 我建议您在UI项目中编辑根_Imports.razor文件,并在其中添加名称空间。 It should look something like this: 它看起来应该像这样:

@using UsComponentLibrary.Lib
@using UsComponentLibrary.Lib.Components
@using UsComponentLibrary.Lib.WhatEverOtherNameSpaceYouNeed

It's also worth noting that the Blazor library project will be depreciated soon and Razor class libraries will be the way to share components for Blazor apps. 还值得注意的是,Blazor库项目将很快折旧,而Razor类库将成为共享Blazor应用程序组件的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM