我将子组件存储在字典中,并尝试从集合中删除键= 1,但最后一行将被删除并且键被操纵。
Initially added child components to parent
After trying to remove the key 1 from the collection
请在下面找到我尝试使用blazor webassembly的描述:
当用户告诉Addme时,我正在将子组件作为renderfragments添加到主组件中的字典中。 同样,当用户提供行号并单击Deleteme时,我正在尝试根据字典键删除renderfragment。 我正在循环字典并显示所有子组件。但是我观察到总是删除字典中的最后一个元素,并且删除后按键错误地指向了Renderfragment。 请帮助我。
Please find the parent component code below:
@page "/counter"
<h1>Counter</h1>
<button class="btn btn-primary" @onclick="IncrementCount">Add me</button>
<br />
<button class="btn btn-primary" @onclick="Remove">Delete me</button>
<label>Enter row number to delete:</label>
<input type="text" @bind-value="@getKey">
<br />
<label>CollectionCount: @dicCount</label>
<label>Counter count: @currentCount</label>
@{
var dic = MyDic.OrderBy(x => x.Key).ToList();
}
@foreach (var item in dic)
{
<br />
<label>Row Number:</label>
<label>@item.Key</label>
@item.Value;
}
@code {
private Dictionary<int, RenderFragment> MyDic { get; set; } = new Dictionary<int, RenderFragment>();
public int getKey { get; set; }
private int currentCount = 0;
private int dicCount = 0;
public RenderFragment ChildRef { get; set; }
private void IncrementCount()
{
ChildRef = builder =>
{
builder.OpenComponent<Child>(1);
builder.CloseComponent();
};
MyDic.Add(currentCount, ChildRef);
ChildRef = null;
dicCount = MyDic.Count;
currentCount++;
}
private void Remove()
{
MyDic.Remove(getKey);
}
}
Please find the child code below:
<h3>Child</h3>
<label>Renderfragment loaded</label>
<label>@RandomNumber</label>
@code {
// Instantiate random number generator.
private readonly Random _random = new Random();
public string RandomNumber { get; set; }
protected override async Task OnInitializedAsync()
{`enter code here`
RandomNumber = _random.Next().ToString();
}
}