我想做简单的组件继承,但是当我导航到 /testpage 时我没有看到任何东西,我做错了什么?
测试基地:
@inherits ComponentBase
@if (!string.IsNullOrEmpty(Name))
{
<h1>@Name</h1>
}
@code {
protected string? Name { get; set; }
public override async Task SetParametersAsync(ParameterView parameters)
{
await base.SetParametersAsync(parameters);
GetInfo();
StateHasChanged();
}
protected virtual void GetInfo()
{
}
}
测试页:
@inherits TestBase
@page "/testpage"
@code {
protected override void GetInfo()
{
Name = "Hello";
}
}
编译页面时,[空白]内容会编译到
BuildRenderTree
中,这会覆盖 BuildRenderTree
中编译到 TestBase
中的内容。
@inherits TestBase
@page "/testpage"
// this is content and overides the content in TestBase
@code {
protected override void GetInfo()
{
Name = "Hello";
}
}
如果你想保留基本组件中声明的内容,你可以这样做:
@inherits ComponentBase
@if (!string.IsNullOrEmpty(Name))
{
<h1>@Name</h1>
}
@code {
protected string? Name { get; set; }
// This is the correct pattern to add any code to SetParametersAsync
public override async Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
GetInfo();
await base.SetParametersAsync(ParameterView.Empty);
}
protected virtual void GetInfo()
{
}
}
然后将页面声明为类[不带
BuildRenderTree
覆盖]:
[Route("/")]
public class HomePage : TestBase
{
protected override void GetInfo()
{
Name = "Hello";
}
}