Исходный код
-------------------------- ReferenceParent3.razor --- компонент предок
@page "/reference-parent-3"
<ul>
@for (int i = 0; i < 5; i++)
{
var index = i;
var v = rendom.Next(1000);
<li>
<ReferenceChild @ref="childComponent" />
<button @onclick ="@( ()=>callChildMethod(index, v) ) >
Индекс компонента @index: Вызов <code>ReferenceChild.ChildMethod(@v)</code>
</button>
</li>
}
</ul>
<hr />
@code {
Random rendom = new Random();
List<ReferenceChild> componets = new List<ReferenceChild>();
Action<int, int> callChildMethod;
ReferenceChild childComponent
{
set => componets.Add(value);
}
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
callChildMethod = CallChildMethod;
}
}
void CallChildMethod(int index, int value)
{
componets.ElementAt(index).ChildMetod(value);
}
}
-------------------------- ReferenceChild.razor --- компонент наследник
@using Microsoft.Extensions.Logging
@inject ILogger<ReferenceChild> logger
@code{
public void ChildMetod(int value)
{
logger.LogInformation("Принято {Value} в ChildMetod метод", value);
}
}