Blazor University (4)组件 — 单向绑定
原文鏈接:https://blazor-university.com/components/one-way-binding/
單向綁定
源代碼[1]
此時我們在頁面內(nèi)顯示了一個組件,但內(nèi)容是靜態(tài)的。我們真正想要的是能夠動態(tài)輸出內(nèi)容。
如果我們更改 /Components/MyFirstComponent.razor 的內(nèi)容,我們可以引入一個私有成員并使用 @ 符號輸出該成員的值。
<div>CurrentCounterValue?in?MyFirstComponent?is?@CurrentCounterValue </div>@code?{private?int?CurrentCounterValue?=?42; }通過參數(shù)接收值
組件內(nèi)的 CurrentCounterValue 總是顯示值“42”,但是如果我們希望父組件告訴我們要顯示哪個值呢?為此,創(chuàng)建一個名為 MySecondComponent 的新組件并從 MyFirstComponent 復(fù)制標(biāo)記,然后將私有成員更改為公共屬性。
<div>CurrentCounterValue?in?MySecondComponent?is?@CurrentCounterValue </div>@code?{public?int?CurrentCounterValue?{?get;?set;?} }編輯 Counter 頁面,添加一個 MySecondComponent 組件,并設(shè)置其 CurrentCounterValue,如下所示:
<MySecondComponent?CurrentCounterValue=@currentCount/>運(yùn)行應(yīng)用程序并導(dǎo)航到 Counter 頁面現(xiàn)在將在瀏覽器的控制臺窗口中顯示錯誤。
WASM:?System.InvalidOperationException:?Object?of?type?‘OneWayBinding.Client.Components.MySecondComponent’?has?a?property?matching?the?name?‘CurrentCounterValue’,?but?it?does?not?have?[ParameterAttribute]?or?[CascadingParameterAttribute]?applied.這清楚地告訴我們?nèi)鄙偈裁?。要向我們的組件添加參數(shù),我們必須使用 [Parameter] 屬性來裝飾我們組件的屬性。
<div>CurrentCounterValue?in?MySecondComponent?is?@CurrentCounterValue </div>@code?{[Parameter]public?int?CurrentCounterValue?{?get;?set;?} }這會通知 Blazor 我們希望我們的組件上有一個參數(shù),該參數(shù)可以通過看起來像 HTML 的屬性進(jìn)行設(shè)置。每當(dāng)重新呈現(xiàn)父組件時,Blazor 也會重新呈現(xiàn)它提供參數(shù)值的任何子組件。這確保子組件被重新渲染以表示通過 [Parameter] 修飾屬性向下傳遞給組件的狀態(tài)的任何可能變化。
如果我們再次運(yùn)行我們的應(yīng)用程序并導(dǎo)航到 Counter 頁面,我們將看到每當(dāng) Counter 頁面中的 currentCount 發(fā)生變化時,它都會通過其 CurrentCounterValue 屬性將該變化推送到我們的嵌入式組件。
注意: 參數(shù)必須是公共屬性。
在繼續(xù)學(xué)習(xí)雙向綁定的工作原理之前,我們首先需要了解組件事件和指令。
參考資料
[1]
源代碼: https://github.com/mrpmorris/blazor-university/tree/master/src/Components/OneWayBinding
總結(jié)
以上是生活随笔為你收集整理的Blazor University (4)组件 — 单向绑定的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET6之MiniAPI(二十五):D
- 下一篇: [活动 3.30]MAUI 跨平台应用开