在 Blazor 动态组件中,要使参数更新,需要在组件的生命周期中手动调用 StateHasChanged 方法。具体来说,在参数发生变化时,应该在 OnParametersSetAsync 方法中调用 StateHasChanged 方法。
示例代码:
@using Microsoft.AspNetCore.Components
@code {
[Parameter] public Type componentType { get; set; }
private RenderFragment componentBody;
protected override async Task OnParametersSetAsync()
{
await base.OnParametersSetAsync();
// update the component body based on the new parameters
componentBody = builder =>
{
builder.OpenComponent(0, componentType);
builder.AddAttribute(1, "Param1", "new value");
builder.CloseComponent();
}
// call StateHasChanged to ensure the update is reflected in the UI
StateHasChanged();
}
}