使用 class sap.ui.core.UIComponent.createContent 创建 Component 实例

发布时间 2023-03-24 23:42:04作者: JerryWang_汪子熙

SAP UI5中,sap.ui.core.UIComponent 和 sap.ui.core.Component 是两个不同的概念,但它们之间有联系。

sap.ui.core.Component是SAP UI5框架中的一个基类,用于封装应用程序或控件。它是应用程序或控件的根级别对象,并负责管理和加载应用程序或控件中的所有资源,包括模型、视图和控制器。sap.ui.core.Component可以通过在manifest.json文件中进行配置来实现。

sap.ui.core.UIComponent是sap.ui.core.Component的子类,是SAP UI5应用程序中的核心组件。它包含应用程序中所有其他组件的定义,例如视图、控制器、模型和服务。它还提供了一个生命周期来管理这些组件,从而使开发人员能够更好地控制应用程序的初始化、销毁和更新。在SAP UI5应用程序中,通常只有一个UIComponent实例。

因此,UIComponent是一个特殊的Component,它定义了整个SAP UI5应用程序的基本结构和生命周期。UIComponent实例化并管理应用程序中所有其他组件,同时提供了一些特定于应用程序的功能,例如路由、事件总线等。

总之,sap.ui.core.Component是SAP UI5框架中所有组件的基类,而sap.ui.core.UIComponent是特殊的基于sap.ui.core.Component的组件,它定义了SAP UI5应用程序的基本结构和生命周期。

而 sap.ui.core.UIComponent.createContent 是用于创建此组件的内容(UI 控件树)的挂钩方法。

此类中的默认实现从该组件的描述符(路径/sap.ui5/rootView)中读取根视图的名称(和可选类型),或者为了向后兼容,仅从静态组件元数据(属性 rootView)中读取名称 . 如果未指定类型,则默认为 XML。 然后该方法调用视图工厂来实例化根视图并返回结果。

当没有根视图配置时,返回null。

如果默认实现不符合需要,这个方法可以被子类覆盖。 子类不限于作为返回类型的视图,而是可以返回任何控件,但只能返回一个控件(但是可以是更大的控件树的根)。

sap.ui.core.UIComponent 子类还可以实现 sap.ui.core.IAsyncContentCreation 接口。

实现此接口时,异步 rootView 的加载和处理将链接到 Component.create 工厂的结果 Promise 中。 可以省略额外的异步标志。 请参见下面的示例 1:

sap.ui.define(["sap/ui/core/UIComponent", "sap/ui/core/Fragment"], function(UIComponent, Fragment) {
    return UIComponent.extend("my.sample", {
        metadata: {
            rootView: {
                viewName: "my.sample.views.Main",
                type: "XML",
                id: "sampleMainView"
            },
            interfaces: ["sap.ui.core.IAsyncContentCreation"]
        }
    });
});

上面这个例子展示了异步创建 XML root view 定义的方法。

示例 2 和 3 显示了子类如何覆盖 createContent 函数以异步运行。 要异步创建根控件,子类必须在元数据中定义 sap.ui.core.IAsyncContentCreation 接口。

下面的代码展示了异步创建 XML root 视图实例的具体步骤:

sap.ui.define(["sap/ui/core/UIComponent", "sap/ui/core/mvc/XMLView"], function(UIComponent, XMLView) {
    return UIComponent.extend("my.sample", {
        metadata: {
            // ...
            interfaces: ["sap.ui.core.IAsyncContentCreation"]
        },
        createContent: function() {
            // Dynamically create a root view
            return XMLView.create({ ... });
        }
    });
});

下面代码展示了异步创建 XML fragment 的方法:

sap.ui.define(["sap/ui/core/UIComponent", "sap/ui/core/Fragment"], function(UIComponent, Fragment) {
    return UIComponent.extend("my.sample", {
        metadata: {
            // ...
            interfaces: ["sap.ui.core.IAsyncContentCreation"]
        },
        createContent: function() {
            // In this use case, a Fragment must only have one single root control.
            // The root control can contain several controls in turn.
            return Fragment.load({ ... });
        }
    });
});