【问题标题】:how to call child component method from parent component in blazor?如何从 blazor 中的父组件调用子组件方法?
【发布时间】:2020-05-19 08:24:25
【问题描述】:

我有两个组件。 第一个组件包括模型列表 第二个组件包含模态形式 我想在第一个组件内单击模型 在第二个组件中,打开 modal 并编辑模型 如何从父组件调用子组件中的show函数

<ChildComponent />
<button onClick="@ShowModal">show modal</button>

@code{
    ChildComponent child; 

    void ShowModal(){
        child.Show();
    }
}

我用过@using 但是 此代码有错误:

找不到类型或命名空间名称 ChildComponent

【问题讨论】:

    标签: blazor asp.net-blazor


    【解决方案1】:

    首先您需要捕获子组件的引用:

    <ChildComponent @ref="child" />
    

    然后您可以使用此引用来调用子组件方法,就像您在代码中所做的那样。

    <button onClick="@ShowModal">show modal</button>
    
    @code{
        ChildComponent child; 
    
        void ShowModal(){
            child.Show();
        }
    }
    

    您的组件的命名空间需要在页面或 _Imports.razor 中通过 using 添加。如果您的组件位于子文件夹 Components/ChildComponent.razor 中,则其命名空间为 {YourAppNameSpace}.Components

    @using MyBlazorApp.Components
    

    read the code

    【讨论】:

    • 你会如何用foreach循环中呈现的子组件编写这个?
    • @JasonAyer 与另一个包含 ChildComponent 的组件和 ChildComponent 的显示模式按钮。所以,实际上只是 foreach 这个。
    • 我只是尝试使用您的代码作为示例,它只调用最后一个渲染组件的方法。不是全部。
    【解决方案2】:

    这是我刚刚发布的关于使用接口的主题的文章:

    https://datajugglerblazor.blogspot.com/2020/01/how-to-use-interfaces-to-communicate.html

    在本例中,索引页是一个 IBlazorComponentParent 对象。

    在登录组件上,最酷的部分是设置 Parent 属性,你只需设置 Parent=this:

    它的工作方式是Login组件上Parent属性的setter调用父组件上的Register方法:

    [Parameter]
    public IBlazorComponentParent Parent
    {
        get { return parent; }
        set 
        { 
            // set the parent
            parent = value;
    
            // if the value for HasParent is true
            if (HasParent)
            {
                // Register with the parent to receive messages from the parent
                Parent.Register(this);
            }
        }
    }
    

    然后在父组件或页面上,Register方法存储对组件的引用:

    public void Register(IBlazorComponent component)
    {
        // If the component object and Children collection both exist
        if (NullHelper.Exists(component, Children))
        {
            // If this is the Login component
            if (component.Name == "Login")
            {
                // Set the Login control
                this.Login = component as Login;
            }
    
            // add this child
            Children.Add(component);
        }
    }
    

    此时,父页面和登录页面可以相互通信,因为它们都包含一个 ReceiveData 方法,您可以在其中发送消息。

    【讨论】:

      猜你喜欢
      • 2022-12-22
      • 2021-06-10
      • 1970-01-01
      • 2021-05-02
      • 2016-12-08
      • 2020-06-15
      • 2018-06-08
      相关资源
      最近更新 更多