Day 11 Arbitrary attributes

目前MyButton有3个[Parameter],如果再增加的话,又要再定义新的[Parameter],为了避免不断更动这个Component,我们来用Blazor提供的@attribute

首先把原本的<button>改为<input>,在MyButton.razor定义一个带有[Parameter]的变数InputAttributes,型别为Dictionary<string, object>,先给预设值,如果外部没有传入这个参数的话就会套用预设值。
https://ithelp.ithome.com.tw/upload/images/20210911/20140893LsnOwyoqsv.png

接着在PostBase.razor.cs也定义一个同名变数,不过里面的valueclass有稍微改动。
https://ithelp.ithome.com.tw/upload/images/20210911/20140893oGKQT4jGwP.png

最後Post.razor叫用的MyButton只传入InputAttributes,这样就完成了。
https://ithelp.ithome.com.tw/upload/images/20210911/20140893wdWT7TSw0u.png

不过好像哪里怪怪的,因为只用了一个变数InputAttributes,导致原本的Reset按钮跟Submit变得一样了,但如果再定义一个为Reset产生的变数,又跟原本一样麻烦了。
https://ithelp.ithome.com.tw/upload/images/20210911/20140893kVcn9uQhFF.png

这时候就要用到[Parameter]的参数CaptureUnmatchedValues了,我们将原本的[Parameter]改成[Parameter(CaptureUnmatchedValues = true)]或是[Parameter(true)]也行,告诉Blazor这个变数会捕捉任何不符合InputAttributes中定义的值。
https://ithelp.ithome.com.tw/upload/images/20210911/20140893aizKQAUZVz.png

接着把PostBase.razor.cs的变数InputAttributes删除,因为不能再这样定义了,我们等一下来看看如果保留的话会有什麽结果。
https://ithelp.ithome.com.tw/upload/images/20210911/20140893Qtu07L8S0l.png

最後PostBase.razor随意给<MyButton>我们想要的html attribute,就可以看到变回Submit跟Reset按钮了,要注意的是因为变成我们自由定义,所以没有了强型别的约束。
https://ithelp.ithome.com.tw/upload/images/20210911/20140893CG1Jayoehg.png
https://ithelp.ithome.com.tw/upload/images/20210911/20140893dBZHEGv2uj.png

这时候有人可能会发现,两个<MyButton>有个相同html attribute type,既然重复,可以定义在PostBase.razor.csInputAttributes吗?
https://ithelp.ithome.com.tw/upload/images/20210911/201408938SVVz0jeqr.pnghttps://ithelp.ithome.com.tw/upload/images/20210911/20140893cOSXXzNAhe.png

可惜错误讯息告诉我们:如果用了CaptureUnmatchedValues就不能明确定义InputAttributes了,所以使用的人须特别注意这点。
https://ithelp.ithome.com.tw/upload/images/20210911/20140893W8kgdiukWE.png

还有一点是html attribute的读取顺序是由右到左,若有重复的html attribute,右边的会覆盖左边的,我们在MyButton.razor@attribute右边加上value="MyButton",开启网页可以看到两颗按钮都变成Mybutton了,所以若要给预设值的话,最好是放在@attribute左边,以免覆盖传进来的值。
https://ithelp.ithome.com.tw/upload/images/20210911/20140893qgxOlKfhEC.png
https://ithelp.ithome.com.tw/upload/images/20210911/20140893ZApdA0GkRR.png

Ref: Blazor Attribute Splatting

Ref: Arbitrary attributes and parameters in Blazor


<<:  Day 7 - 拯救落後的专案能撑一天是一天(前端篇)

>>:  Day11 - Google Kubernetes Engine(GKE) 轻松架起 k8s 环境

JavaScript Day 8. 浅谈 Function-操作实例

上一篇大略的说明了 function 的两个大类别,这里试着放比较多的简易操作实例。 注册多组函式 ...

[Day 9] Reactive Programming - Backpressure

前言 大部分介绍Reactive Programming都一定会提到Backpressure,可能放...

Day15 - 模型评估 part2

前面提到过使用不同架构(FCDAE(3h),FCDAE(5h))的全连接神经网路除噪模型对两个语音特...

DAY10-EXCEL统计分析:信赖区间

平均数的信赖区间 若想知道一个班级学期成绩的90%信赖区间 首先建立学生学期成绩的资料 点选工具表中...

使相机看着目标

大家好,我是西瓜,你现在看到的是 2021 iThome 铁人赛『如何在网页中绘制 3D 场景?从 ...