在blazor中添加动态组件列表 [英] add list of dynamic components in blazor
问题描述
我刚刚开始了解blazor(v0.3),并做了一些测试,我想使用blazor添加列表
I just started to have a look in blazor (v0.3) and doing some test I wanted to add a list using blazor
首先,我创建了List<string>
来测试同一页面中的简单列表
First I created a List<string>
to test a simple list in the same page
<ul>
@foreach (var item in listItems)
{
<li>@item</li>
}
</ul>
@functions {
private List<string> listItems = new List<string>();
private string newItem;
private void AddItem()
{
if (string.IsNullOrEmpty(newItem))
return;
listItems.Add(newItem);
newItem = "";
}
}
这工作正常,将所有元素添加到列表中.但是,根据这个问题,我尝试添加组件,添加单个组件很容易,这里,但是对于列表,我遇到了下一个问题:
this is working fine, is adding every element to the list when I add it. but then, i tried to add components, add a single component was easy, based on this question here but for a list I had the next problem:
- 我创建了一个
<li>
组件只是为了测试组件的功能,这是组件视图
- I created a
<li>
compontent just to test the functionality of components, here is the component view
<li id="@ID">
@Text
</li>
@functions {
[Parameter]
string Text { get; set; }
[Parameter]
string ID { get; set; }
}
- 然后在父视图中
<input type="text" bind="TxtExample" name="inpAdd"/>
<button onclick="@addCompoment">add comp1</button>
<div class="simple-list-list">
@if (!componentListTest.Any())
{
<p>You have no items in your list</p>
}
else
{
<ul>
@foreach (var item in componentListTest)
{
@item
}
</ul>
}
</div>
@functions {
private List<RenderFragment> componentListTest { get; set; }
private int currentCount {get; set;}
private string TxtExample { get; set; }
protected override void OnInit()
{
currentCount = 0;
componentListTest = new List<RenderFragment>();
}
protected void addCompoment()
{
componentListTest.Add(CreateDynamicComponent(currentCount));
currentCount++;
}
RenderFragment CreateDynamicComponent(int counter) => builder =>
{
var seq = 0;
builder.OpenComponent(seq, typeof(listExample));
builder.AddAttribute(++seq, "Text", "text -- "+TxtExample);
builder.AddAttribute(++seq, "id","listed-"+counter);
builder.CloseComponent();
};
}
当我加载拳头元素时,正确加载了:
when I load the fist element is loaded correctly:
但是当我输入第二个时,所有这些都被替换为最后一个:
but when I entered the second one, all of them are replaced for the last one:
有什么想法吗?
推荐答案
您使它变得太复杂了.您无需动态实例化组件即可使此方案正常工作.
You are making it too complicated. You don't need to dynamically instantiate components for this scenario to work.
您可以执行以下操作:
<ul>
@foreach (var item in listItems)
{
<myComponent bind-myVar="@item"></myComponent>
}
</ul>
组件将为您实例化.
另请参见此处如何使参数在您的组件上起作用.
Also see here how to make the parameters work on your component.
这篇关于在blazor中添加动态组件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!