gpt4 book ai didi

blazor - 如何获取自定义 Blazor 组件的特定实例

转载 作者:行者123 更新时间:2023-12-03 21:17:03 26 4
gpt4 key购买 nike

来自 asp.net webforms 我总是有些怀疑如何在 Blazor 中实现某些任务,没有引用控件或组件的唯一 ID。

假设我有一个名为 MyCard(一个简单的引导卡)的自定义组件,它公开了一个 Visible 属性

<div class="card mb-3 @display" style="width: 18rem;">
<div class="card-body">
@ChildContent
</div>
</div>


@code {
string display = "";

[Parameter]
public RenderFragment ChildContent { get; set; }

private bool _visible = true;
[Parameter]
public bool Visible
{
get
{
return _visible;
}
set
{
_visible = value;
display = value ? "" : "d-none";
}
}

}

然后我在一页上使用多个
@page "/"

<h1>Hello, world!</h1>

<MyCard Visible="@hidetoggles[0]">First Card</MyCard>

<MyCard Visible="@hidetoggles[1]">Second Card</MyCard>

<MyCard Visible="@hidetoggles[2]">Third Card</MyCard>

<button @onclick="Hide">Hide the 2nd card</button>

@code
{
bool[] hidetoggles = new bool[] { true, true, true };

void Hide()
{
hidetoggles[1] = false;
}
}

有没有更优雅的方法来设置特定实例(例如第二个)的属性而不是我所做的?

MyCard 中的 ID 属性有用吗?

谢谢

最佳答案

报价Capture references to components文档:

Component references provide a way to reference a component instance so that you can issue commands to that instance, such as Show or Reset. To capture a component reference:

  • Add an @ref attribute to the child component.
  • Define a field with the same type as the child component.

对于您的代码:
MyCard.razor:
<div class="card mb-3 @display" style="width: 18rem;">
<div class="card-body">
@ChildContent
</div>
</div>

@code {
string display = "";

[Parameter]
public RenderFragment ChildContent { get; set; }

public void setVisible(bool visible)
{
if(visible)
{
display = "";
}
else
{
display = "d-none";
}
}
}
Index.razor:
<MyCard @ref="MyCardControl1">First Card</MyCard>
<button @onclick="Hide">Hide card</button>
@code{

MyCard MyCardControl1;

private void Hide()
{
MyCardControl1.setVisible(false);
}
}
更多信息请访问 Blazor Binding, Events and Parameters .

关于blazor - 如何获取自定义 Blazor 组件的特定实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59446464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com