0

我正在使用 DinamicComponent 渲染组件,我需要调用在子组件中找到的函数。我找不到对 DinamicComponents 使用 @ref 的等价物,以便我可以引用来调用该函数。

这是父组件

 <div class="tab-content">
            @foreach (VerticalTabComponent.TabModel oneTabItem in VerticalTabsList)
            {
                <div class="tab-pane fade show @(oneTabItem.TabIndex == SelectedTabIndex ? "active" : "")" @key=@($"VTabDivDynamic_{TabPrefix}_{oneTabItem.TabIndex.ToString()}")>
                    <DynamicComponent
                              Type=@System.Type.GetType(oneTabItem.TabComponent)
                              Parameters=@oneTabItem.TabParameters>
                    </DynamicComponent>
                </div>
            }
        </div>

这是 Blazor 组件选项卡中的代码

 public partial class TabComponent
{
    [Parameter]
    public EventCallback<string> InsertUpdateCallback { get; set; }

    
    protected override async Task OnInitializedAsync()
    {
       await CallAnyfunctionAsync();
    }
    private async Task<bool> LoadDataGrid()
    {
       //this is the function I need to call from parent
    }
}

如何从父组件调用 Load Grid 函数?

4

1 回答 1

0

通常在 Blazor 中,我们用于@Ref获取对组件的引用,但正如您所见,这不适用于DynamicComponent.

一种解决方法是向[Parameter]组件添加一个名为类似的东西Register,这是一个将泛型类型设置为组件类型的操作。然后,您可以添加代码来处理OnParametersSet以在组件中调用此方法。

然后,您可以在您的参数中添加一个Register参数,TabParameters该参数会通过引用进行更新。

下面的示例代码将添加到SurveyPrompt组件中:

    /// <summary>
    ///  will be called when params set
    /// </summary>
    [Parameter] public  Action<SurveyPrompt> Register { get; set; }

    protected override void OnParametersSet()
    {
        if (Register != null)
        {
            // register this component
                Register(this);
        }
    }

您添加一个Register带有Action<type>值的参数。这是一个例子:

    SurveyPrompt sp1 = null;


    void Register1(SurveyPrompt survey)
    {
        sp1 = survey;
        Console.WriteLine("SP1 has title " + sp1.Title);
    }

    protected override void OnInitialized()
    {
        Action<SurveyPrompt> p1 = Register1;

        params1 = new Dictionary<string, object>()
        {
            { "Title", "Survey Title Here" },
            { "Register", p1 }
        };
    }

    IDictionary<string, object> params1;

于 2021-05-26T08:19:21.980 回答