是否可以让孩子加入自定义组件?

<myCustomComponent>
    <Label #id1 text="ID 1"></Label>
    <Label #id2 text="ID 2"></Label>
</myCustomComponent>

有没有办法获取这两个Lable的引用,以将它们放置在我的自定义组件中的GridLayout中?

最佳答案

除了具有getViewById()的选项外,还有几个选项可用于查看布局的子项或其索引,以及添加,删除,插入和重置子项。

例如
page.xml

<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
    <StackLayout id="st" class="p-20">
        <Label id="lbl-title" text="Tap the button" class="h1 text-center"/>
        <Button text="TAP" tap="{{ onTap }}" class="btn btn-primary btn-active"/>
        <Label text="{{ message }}" class="h2 text-center" textWrap="true"/>
    </StackLayout>
</Page>

page.ts
let page = <Page>args.object;
let stack = <StackLayout>page.getViewById("st");
let label = <Label>page.getViewById("lbl-title");

console.log("page.content: " + page.content); // page.content: StackLayout<st>@file:///app/main-page.xml:19:5;

console.log("stack.getChildrenCount(): " + stack.getChildrenCount()) // 3
console.log("stack.getChildAt(1): " + stack.getChildAt(1)); // stack.getChildAt(1): Button(5)@file:///app/main-page.xml:21:9;
console.log("stack.getChildIndex(label): " + stack.getChildIndex(label)); // 0

console.log("stack.parent: " + stack.parent); // stack.parent: Page(1)@file:///app/main-page.xml:7:1;

var newlabel = new Label();
newlabel.text = "new Label";
stack.addChild(newlabel);

有关所有受支持方法here的更多信息

关于nativescript - 是否可以让 child 加入自定义组件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41698218/

10-08 23:23