簡體   English   中英

如何創建 blazor 組件?

[英]How can i create a blazor component?

我的警報類是

namespace RazorComponents.Models
{
    public class Alert
    {
        public string Title { get; set; }
        public string Text { get; set; }
        public bool Dismissible { get; set; }
    }
}

我的 AlertComponent 是

namespace RazorComponents.Test
{
    public partial class AlertComponent : ComponentBase
    {
        public Alert Alert { get; set; }
    }
}

有以下觀點

@using Models
  
<div class="alert alert-warning alert-dismissible fade show" role="alert">
    <strong>@Alert.Title</strong> You should check in on some of those fields below.
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
</div>

返回編譯時錯誤C# An object reference is required for the non-static field, method, or property @Alert.TitleC# An object reference is required for the non-static field, method, or property

這是正常的,但如何將 Alert 類作為視圖中的模型傳遞?

至少在 MVC 中,我們可以選擇@model Alert並通過模型傳遞
async Task<IViewComponentResult> InvokeAsync

您需要像這樣向組件添加代碼塊:

@code
{
    [Parameter]
    private Alert Alert { get; set };
}

僅當您想從外部(從另一個組件)設置值時才添加 [Parameter] 屬性。

您需要將[Parameter]屬性添加到Alert屬性中:

namespace RazorComponents.Test
{
    public partial class AlertComponent : ComponentBase
    {
        [Parameter]
        public Alert Alert { get; set; }
    }
}

要使用您的組件,只需將您的警報作為參數傳遞,如下所示:

<AlertComponent Alert="Alert"/>

@code
{
    public Alert Alert {get; set;}
}

定義類背后的代碼:

AlertComponent.razor.cs

public partial class AlertComponent
    {
        [Parameter]
        public Alert Alert { get; set; }

        [Parameter]
        public EventCallback Close { get; set; }
     
    }

你需要在這里: using Microsoft.AspNetCore.Components;

注意:EventCallback Close 參數用於調用打開警報的方法將其關閉。

定義 AlertComponent 的視圖部分

AlertComponent.razor

<div class="alert alert-warning alert-dismissible fade show" role="alert">
    <strong>@Alert.Title</strong> <div>@Alert.Text</div>
    <button @onclick="@(() => Close.InvokeAsync())" type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
</div>

@code {   
}

用法:

@page "/"

@if (alert != null)
 {
    <AlertComponent Alert="alert" Close="Close" />
 }

<button @onclick="ShowAlert">Display alert</button>

@code
{
    private Alert alert;

    private void ShowAlert()
    {
        alert = new Alert() { Title = "My alert", Text = "You are being alerted", Dismissible = true };
    }
    private void Close()
    {
        alert = null;
    }
}

當您單擊“顯示警報”按鈕時,會創建一個新的 Alert 實例,重新渲染 Page 組件,這次alert != null為真,從而渲染了 AlertComponent。 當點擊AlertComponent中的“關閉按鈕”時,Index組件中定義的Close方法將alert變量的值設置為null,之后Index組件重新渲染,這次AlertComponent不會重新渲染因為警報變量的值為空。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM