要解决Blazor中修改CaptureUnmatchedValues现有属性不会重新渲染的问题,可以使用以下解决方法:
public class CustomComponent : ComponentBase
{
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary AdditionalAttributes { get; set; }
protected override async Task OnParametersSetAsync()
{
await base.OnParametersSetAsync();
StateHasChanged();
}
}
@code {
private Dictionary myAttributes;
protected override void OnInitialized()
{
myAttributes = new Dictionary
{
{ "class", "my-class" },
{ "style", "color:red" }
};
}
}
这样,当myAttributes属性发生更改时,CustomComponent将重新渲染。
请注意,由于Blazor对属性的更改追踪是基于引用的,因此如果要在属性更改时重新渲染组件,必须确保每次更改时都创建一个新的属性实例。