Blazor University (11)组件 — 替换子组件的属性

原文链接:https://blazor-university.com/components/replacing-attributes-on-child-components/

替换子组件的属性

源代码[1]

到目前为止,我们已经了解了如何创建代码生成的属性[2],以及如何捕获意外参数[3]。除了这两种技术之外,Blazor 还允许我们重写/替换子组件中的现有属性。

采取以下页面标记:

它使用以下子组件:


  Right-click and inspect the HTML for this element to see the results!
@code {   [Parameter(CaptureUnmatchedValues=true)]   public Dictionary AllOtherAttributes { get; set; } }

正如我们之前在代码生成的属性[4]中看到的那样,ChildComponent 会将使用者提供的属性(第一个和第二个)捕获到我们的参数 AllOtherAttributes 中,并且对 @attributes=AllOtherAttributes 的调用将指示 Blazor 在 Dictionary 中输出名称/值对。前面的代码将输出以下 HTML。


  Right-click and inspect the HTML for this element to see the results!

替换子属性

如果我们想为 firstsecond 指定默认值以在使用者不提供它们时输出怎么办?如果未设置值,则可能很容易重写 SetParametersAsync[5] 并插入值,但有一种更简单的方法!

我们所要做的就是写出我们的默认值作为子组件标记的一部分,@attributes= 指令将使用使用者传递的任何值覆盖它们。因此,如果我们更改子组件以指定一些默认属性值,如下所示:


  Right-click and inspect the HTML for this element to see the results!

然后我们可以像这样替换组件的那些默认值:

这将呈现以下 HTML:


  Right-click and inspect the HTML for this element to see the results!

我们的子组件将始终呈现其所有四个 HTML 属性,但也将允许使用者替换它们的值。

保护属性不被替换

在某些情况下,我们可能希望允许组件的使用者替换某些属性,但我们希望保护其他属性不被更改。例如:

在这个假设的 InputNumber 控件中,我们希望允许我们的使用者替换默认的 CSS 类属性,但不希望他们意外地将 typenumber 更改为 checkbox

在 Blazor 中,我们的 @attributes= 指令的位置很重要。指令之前的任何属性(在其上方或左侧)都可以由使用者替换其值,但在它之后(在其下方或右侧)的所有属性都受到保护,以免其值被替换。

鉴于以下标记:

然后调整 @attributes= 在我们的 ChildComponent 中的位置将为我们提供以下输出:

// Example 1
// Generated HTML
// Example 2
// Generated HTML
// Example 3
// Generated HTML

Blazor University (11)组件 — 替换子组件的属性_第1张图片

参考资料

[1]

源代码: https://blazor-university.com/components/replacing-attributes-on-child-components/

你可能感兴趣的:(java,html,vue,javascript,python)