如何在NativeScript TypeScript中动态创建xml组件 [英] How to create xml component dynamically in nativescript typescript

查看:249
本文介绍了如何在NativeScript TypeScript中动态创建xml组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加其他组件,例如布局,按钮,图像等...

I want to add another component like layout, button, image, etc...

这是我的xml代码,我想在ID为聊天框"的stacklayout上添加xml:

This my xml code and I want to add xml on stacklayout which ID is "chatbox":

<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>

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

Here's my current typescript code but it doesn't work. It doesn't even show compile error.

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();                }

推荐答案

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

Now if you are using page reference you can use getViewById to access the Stacklayout container via its unique ID.

例如 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>

TypeScript

TypeScript

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);;
}

或者您可以通过某些Page生命周期事件来访问Page引用

Or you could access the Page refence via some of the Page lifecycles events

XML

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

TypeScript

TypeScript

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);;
}

此处的游乐场演示(请注意,该演示正在使用带有TypeScript语言的NativeScript核心).对于Angular,您可以在组件构造函数中通过DI使用Angular ViewCHild或Page引用.

Playground demo here (note that the demo is using NativeScript Core with TypeScript language). For Angular, you could use Angular ViewCHild or Page reference via DI in the componentes constructor.

这篇关于如何在NativeScript TypeScript中动态创建xml组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆