Blazor WebAssembly_自行元件封裝part1.與css 的 isolation

 
在Blazor當中若要去設定事件的callback寫法很單純
針對Button前端的元素我們可以加上@onclick後頭捕上
lambda expression的匿名方法或者具名方法


而元件封裝跟過去webform時代的ascx 其實很像
額外定義一個razor元件

~\Pages\Alert.razor

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@if (Show)
{
    <div class="dialog-container">
        <div class="dialog">
            <div>
                @ChildContent
            </div>
            <div>
                <button @onclick="OnOk">
                    OK
                </button>
            </div>
        </div>
    </div>
}
@code {
    [Parameter] public bool Show { get; set; }
    [Parameter] public EventCallback OnOk { get; set; }
    [Parameter]
    public RenderFragment ChildContent
    {
        get;
        set;
    }
}

[Parameter]修飾的屬性
則代表可從父元件傳遞進來給當前這個子元件的意思

EventCallback 則是對外可去指定要呼叫的客製化委派(也就是方法回呼)

RenderFragment 則代表這個子元件也就是open/close tag裡面你可以填入取代的內文block
你可以從父元件傳入新型的子元件template
在這當中的block是可被抽換與彈性配置的

~\Pages\Index.razor

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />
<Counter />


<Alert Show="showAlert" OnOk="@(() => showAlert=false)">
    <h1>alert title</h1>
    <p>Today is @DateTime.Now.DayOfWeek.</p>    
</Alert>

<button @onclick="@(() => showAlert=true)">
    show alert1
</button>

<Alert Show="showAlert2" OnOk="OkClickHandler">
    <h1>alert title2</h1>
    <p>this is RenderFragment content1 @DateTime.Now</p>
</Alert>

<button @onclick="@(() => showAlert2=true)">
    show alert2
</button>

@code {
    private bool showAlert = false;
    private bool showAlert2 = false;

    private void OkClickHandler()
    {
        showAlert2 = false;
    }

}


Blazor元件中也可實作css 的 isolation
通常會命名跟元件檔案名稱一樣



~\Pages\Alert.razor.css

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
.dialog-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0,0,0,0.6);
    z-index: 2000;
}

.dialog {
    background-color: white;
    margin: auto;
    width: 15rem;
    padding: .5rem
}

















留言

這個網誌中的熱門文章

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header

經得起原始碼資安弱點掃描的程式設計習慣培養(三)_7.Cross Site Scripting(XSS)_Stored XSS_Reflected XSS All Clients

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題