目录
- 如何实现在react现有项目中嵌入Blazor?
 - 首先流程
 
如何实现在react现有项目中嵌入Blazor?
目前官方只提供了angular和react俩种示例所以本教程只讲react教程
思路讲解:
首先在现有react项目中我们可能某些组件是在Blazor中完成,但是我们没办法找到怎么在react中轻量级使用blazor组件,可能会有人会使用iframe去加载Blazor项目,但是我不太喜欢这种方式,所以今天问了很多大佬,有大佬说可以直接在react使用Blazor组件的方式,并且找到了文档和示例(其实在Blazor文档中微软已经提到了这个但是由于在文档的在下面的示例中可能没什么人去看 [文档直通车](ASP.NET Core Razor 组件 | Microsoft Learn))
首先流程
创建react项目
npx create-react-app react-debug cd react-debug yarn or npm i
将以下代码添加到App.js
import React, { useState } from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
    const [nextCounterIndex, setNextCounterIndex] = useState(1);
    const [blazorCounters, setBlazorCounters] = useState([]);
    const addBlazorCounter = () => {
        const index = nextCounterIndex;
        setNextCounterIndex(index + 1);
        setBlazorCounters(blazorCounters.concat([{
            title: `Counter ${index}`,
            incrementAmount: index,
        }]));
    };
    const removeBlazorCounter = () => {
        setBlazorCounters(blazorCounters.slice(0, -1));
    };
    return (
        <div className="App">
            <header className="App-header">
                <img src={logo} className="App-logo" alt="logo" />
                <p>
                    <button onClick={addBlazorCounter}>Add Blazor counter</button>  
                    <button onClick={removeBlazorCounter}>Remove Blazor counter</button>
                </p>
    
                {blazorCounters.map(counter =>
                    <div key={counter.title}>
                        <my-blazor-counter title={counter.title} increment-amount={counter.incrementAmount}></my-blazor-counter> // 这里将是渲染razor组件的地方 `my-blazor-counter` 是在razor中定义的,会在下面讲到 
                    </div>
                )}
    
            </header>
        </div>
    );
}
export default App;
将以下引用添加到public/index.html中 Microsoft.AspNetCore.Components.CustomElements/BlazorCustomElements.js是Microsoft.AspNetCore.Components.CustomElements 生成的
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="https://www.freexyz.cn/dev/%PUBLIC_URL%/favicon.ico" rel="external nofollow"  />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="https://www.freexyz.cn/dev/%PUBLIC_URL%/logo192.png" rel="external nofollow"  />
    <link rel="manifest" href="https://www.freexyz.cn/dev/%PUBLIC_URL%/manifest.json" rel="external nofollow"  />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script src="https://www.freexyz.cn/dev/_content/Microsoft.AspNetCore.Components.CustomElements/BlazorCustomElements.js"></script> 
    <script src="https://www.freexyz.cn/dev/_framework/blazor.webassembly.js"></script>
  </body>
</html>
创建WebAssembly项目
mkdir webassembly cd webassembly dotnet new blazorwasm-empty
WebAssembly文件夹 并且在文件夹中创建 WebAssembly的空项目
需要确保项目是7.0 因为目前只支持6的预览和7的正式版
安装 Microsoft.AspNetCore.Components.CustomElements
<PackageReference="Microsoft.AspNetCore.Components.CustomElements" Version="7.0.2" />
Microsoft.AspNetCore.Components.CustomElements 是提供组件化的主要实现
修改Program.cs的代码
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
// BlazorApp.Pages.Index可以修改成自己的渲染的razor组件
// my-blazor-counter就是上面提到的razor对应的标记 这样就可以在react通过my-blazor-counter去渲染BlazorApp.Pages.Index组件的内容了
builder.RootComponents.RegisterCustomElement<webassembly.Pages.Index>("my-blazor-counter");
builder.RootComponents.Add<HeadOutlet>("head::after");
await builder.Build().RunAsync();
webassembly.Pages.Index组件相关代码
<h1>@Title</h1>
<p role="status">Current count: @currentCount</p>
<p>Increment amount: @IncrementAmount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
    private int currentCount = 0;
    
    [Parameter] public string Title { get; set; } = "Blazor Counter";
    [Parameter] public int? IncrementAmount { get; set; }
    private void IncrementCount()
    {
        currentCount += IncrementAmount.GetValueOrDefault(1);
    }
}
<style>
    button {
        font-weight: bold;
        background-color: #7b31b8;
        color: white;
        border-radius: 4px;
        padding: 4px 12px;
        border: none;
    }
    button:hover {
        background-color: #9654cc;
        cursor: pointer;
    }
    button:active {
        background-color: #b174e4;
    }
</style>
如何查看运行效果:
如果需要查看运行效果有很多种方式比如通过代码将Blazor和react的代理到一块这样就可以一边修改一边预览,
但是我现在做最简单的
先将react build生成
yarn build
将build目录下面的所有文件拷贝到webassembly\wwwroot下,并且覆盖index.html
然后执行dotnet程序 在webassembly目录下执行
dotnet watch
将会打开浏览器 ,效果入下图,我们可以添加 Add Blazor counter

效果将是这样,可以点击Click me将会条件 Current count数量 点击Remove Blazor counter将会删除razor组件

好了效果差不多是这样字,
通过这个案例我们可以知道 blazor也可以像react那样嵌入在任何的现有项目中,并且使用方便,如果是vue的话目前还不知道是否支持 目前官方只提供了angular和react俩种实现,并且支持webassembly和server,当前教程是WebAssembly的实践,Server会有所差异,

评论(0)