在 blazor 專案中,我創建了一個 public class BaseComponent : Microsoft.AspNetCore.Components.ComponentBase
所以我希望從這個類繼承一些有點復雜的組件。
現在,我添加了一個錯誤頁面,在覆寫函式時我看到了一些不一致OnInitialized,但似乎這不僅限于該函式。
這Error.razor是編譯沒有錯誤的檔案:
@inherits BaseComponent
@code {
protected override void OnInitialized()
{
base.OnInitialized();
}
}
當我想將所有代碼移動到Error.razor.cs檔案時:
using WebApp.Shared;
namespace WebApp.Pages.Error
{
public partial class Error : BaseComponent
{
protected override void OnInitialized() // error is here
{
base.OnInitialized();
}
}
}
我收到一條錯誤訊息:'Error.OnInitialized()': no suitable method found to override。
我已經嘗試讓Error.razor.cs部分類繼承自Microsoft.AspNetCore.Components.ComponentBasemy BaseComponent,而不是繼承這個類并且具有OnInitialized函式本身的覆寫,并且它不會給出任何編譯錯誤。
所以我的問題是:
為什么.razor檔案中沒有編譯錯誤,但.razor.cs檔案中有?
uj5u.com熱心網友回復:
這是您可能希望用作模板的示例基本組件和用法。
筆記:
- 我已經將基礎組件變成了一個類,而不是一個剃刀組件。任何孩子幾乎肯定會覆寫內容。
- 我已將基類設定為
abstract不能直接使用。 - 我已經在所有內容中設定了命名空間。
// Components/MyComponentBase.cs
namespace StackOverflowAnswers.Components
{
public abstract class MyComponentBase : ComponentBase
{
[Parameter] [EditorRequired] public string Header { get; set; } = String.Empty;
[Parameter] public RenderFragment? ChildContent { get; set; }
}
}
// Components/MyDiv.razor
@namespace StackOverflowAnswers.Components
@inherits MyComponentBase
<h3>@this.Header</h3>
<div class="m-2">
@this.ChildContent
</div>
// Components/MyDiv.razor.cs
namespace StackOverflowAnswers.Components
{
public partial class MyDiv : MyComponentBase
{
protected override void OnInitialized()
{
base.OnInitialized();
}
}
}
以及在Index.razor 中的用法
@page "/"
@page "/Index"
@using StackOverflowAnswers
<PageTitle>Index</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
<StackOverflowAnswers.Components.MyDiv Header = "Hello Blazor">
My Div Content
</StackOverflowAnswers.Components.MyDiv>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/403388.html
標籤:
