DynamicComponent 更改组件类型时不刷新

问题描述 投票:0回答:1

```

我需要根据所选类型渲染组件。

这就是我的设置方式:-

SelectedQuestionTemplate = Type.GetType($"CheetahExam.WebUI.Client.Pages.Exam.Questions.Templates.CheckBoxTemplate2");
**Parameters** = 
 parameters["ExamId"] = ExamId;
 parameters["QuestionId"] = SelectedQuestionId;
 parameters["OnDelete"] = EventCallback.Factory.Create<bool>(
                                         this, HandleQuestionDelete);
 parameters["OnSave"] = EventCallback.Factory.Create<bool>(
                                         this, HandleQuestionSave);

 if (SelectedQuestionType == (int)QuestionTypes.CheckBox)
 {
     SelectedQuestionTemplate = Type.GetType($"CheetahExam.WebUI.Client.Pages.Exam.Questions.Templates.CheckBoxTemplate2");
 }

SelectedQuestionTemplate 获取更改时,它不会刷新动态组件,我的技术堆栈是 blazor webassebly 、.net 7 和 C# 11,

我遵循以下代码(https://learn.microsoft.com/en-us/aspnet/core/blazor/components/dynamiccomponent?view=aspnetcore-7.0


<DynamicComponent Type="typeof({COMPONENT})" @ref="dc" />

<button @onclick="Refresh">Refresh</button>

@code {
    private DynamicComponent? dc;

    private Task Refresh()
    {
        return (dc?.Instance as IRefreshable)?.Refresh();
    }
}

我想实现基于所选类型和参数动态渲染组件

https://learn.microsoft.com/en-us/aspnet/core/blazor/components/dynamiccomponent?view=aspnetcore-7.0`

blazor render blazor-webassembly dynamic-components
1个回答
0
投票

我认为你的主要问题是在这一行

<DynamicComponent Type="typeof({COMPONENT})" @ref="dc" />

{COMPONENT}
表示实部。

这是一个更简单的工作示例,您可以将其粘贴到标准模板中的Home中:

@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<div>
    <button class="btn btn-primary mb-3" @onclick="this.OnClick">Switch</button>
</div>

<DynamicComponent Type="_activeComponent" Parameters="_parameters" />

@code{
    private Type _activeComponent = typeof(Counter);
    private Dictionary<string, object> _parameters = new();

    private Task OnClick()
    {
        if (_activeComponent == typeof(Counter))
        {
            _activeComponent = typeof(Weather);
            _parameters = new();
        }
        else
        {
            _activeComponent = typeof(Counter);
            _parameters = new();
        }

        return Task.CompletedTask;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.