这是honkmother(https://github.com/honkmother)是如何做到的。这是链接:
https ://github.com/aspnet/Blazor/issues/842#issuecomment-490671409
Index.cshtml:
@page "{*clientPath}"
<!DOCTYPE html>
<html>
@(await Html.RenderComponentAsync<html>())
</html>
然后两个类称为“html”和“metatags”。html 类创建 html 标记并将标头(脚本标记等)存储在作为标记注入的 html 文件中。
public class html : ComponentBase
{
public static string HeadTXT = File.ReadAllText("head.htm");
Metatags meta = new Metatags() { Title = "some title" };
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder builder)
{
builder.OpenElement(0, "head");
builder.AddMarkupContent(1, HeadTXT);
builder.OpenComponent<Head>(2);
builder.AddAttribute(3, "MetaInfo", meta);
builder.CloseComponent();
builder.CloseElement();
builder.OpenElement(4, "body");
builder.OpenComponent<Body>(5);
builder.AddAttribute(6, "MetaInfo", meta);
builder.CloseComponent();
builder.AddMarkupContent(7, "<script src=\"_framework/components.server.js\"></script>");
builder.CloseElement();
}
}
public class Metatags
{
public string Title { get; set; } = "example.nyc — weirdest hack ever";
public string Description { get; set; } = "testing";
public Head Component;
}
一个“身体”组件。
<DetectPrerender MetaInfo="@MetaInfo">
<Router AppAssembly="typeof(Startup).Assembly" />
</DetectPrerender>
@functions {
[Parameter]
private Metatags MetaInfo { get; set; }
}
和一个“头”组件。
@using example.Shared
<title>@MetaInfo.Title</title>
<meta name="description" content="@MetaInfo.Description">
@{
MetaInfo.Component = this;
}
@functions {
[Parameter]
private Metatags MetaInfo { get; set; }
private bool ShouldRend = false;
protected override bool ShouldRender()
{
if (ShouldRend)
{
ShouldRend = false;
return true;
}
return false;
}
public void ShouldRe()
{
ShouldRend = true;
base.Invoke(() => base.StateHasChanged());
}
}