【问题标题】:How to create xml component dynamically in nativescript typescript如何在 nativescript typescript 中动态创建 xml 组件
【发布时间】:2018-09-12 21:19:53
【问题描述】:

我想添加另一个组件,例如布局、按钮、图像等...

这是我的 xml 代码,我想在 ID 为“chatbox”的 stacklayout 上添加 xml:

<GridLayout orientation="vertical" rows="*, auto" columns="auto,*, auto"> 
    <ScrollView row="0" colSpan="3" col="0">
         <StackLayout id="chatbox">
              // I want to add XML component here dynamically
         </StackLayout>
    </ScrollView>

这是我当前的打字稿代码,但它不起作用。它甚至不显示编译错误。

export function onSendButtonTap(args: EventData){

const button = <Button>args.object;
const bindingContext = <HomeViewModel>button.bindingContext;

const page = <Page>args.object;
const stack = new StackLayout();
stack.getViewById("chatbox");
const label = new Label();
label.text = "label";
stack.addChild(label);;
bindingContext.sendMessage();                }

【问题讨论】:

    标签: xml typescript nativescript


    【解决方案1】:

    现在,如果您使用页面引用,则可以使用 getViewById 通过其唯一 ID 访问 Stacklayout 容器。

    例如 XML

    <GridLayout rows="100, *">
        <Button row="0" text="Tap to add Label" tap="onButtonTap" />
        <StackLayout row="1" id="chatbox">
            // When you tap the button the label will be added here
        </StackLayout>
    </GridLayout>
    

    打字稿

    onButtonTap(args: EventData): void {
        console.log("Button was pressed");
        const myButton = <Button>args.object;
        const page = myButton.page; // getting page reference via the button object
    
        const stack = <StackLayout>page.getViewById("chatbox");
        const label = new Label();
        label.text = "My New Label";
        stack.addChild(label);;
    }
    

    或者您可以通过一些页面生命周期事件访问页面引用

    XML

    <Page loaded="pageLoaded" class="page">
    

    打字稿

    export function pageLoaded(args: EventData) {
        let page = <Page>args.object;
        const stack = <StackLayout>page.getViewById("chatbox");
        const label = new Label();
        label.text = "My New Label";
        stack.addChild(label);;
    }
    

    Playground demo here(请注意,演示使用的是带有 TypeScript 语言的 NativeScript Core)。对于 Angular,您可以在组件构造函数中通过 DI 使用 Angular ViewCHild 或 Page 引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      • 2022-12-20
      • 2021-03-26
      • 1970-01-01
      • 2020-04-03
      • 2016-12-07
      • 2021-08-25
      相关资源
      最近更新 更多