是否可以让孩子进入自定义组件?
<myCustomComponent>
<Label #id1 text="ID 1"></Label>
<Label #id2 text="ID 2"></Label>
</myCustomComponent>
有没有办法获取这两个Lable
的引用,以便将它们放在我的自定义组件的GridLayout
中?
答案 0 :(得分:5)
除了getViewById()选项外,还有几个选项可以查看布局的子项或其索引,还可以添加,删除,插入和重置子项。
e.g。 的 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
答案 1 :(得分:2)
为此目的,视图类有getViewById()方法。
在my-component.xml中:
<StackLayout loaded="onLoaded">
<Label id="label1" text="ID 1" mycustomattribute="Hi there."></Label>
<Label id="label2" text="ID 2"></Label>
</StackLayout>
在my-component.js中:
exports.onLoaded = function(args) {
let view = args.object;
let label1 = view.getViewById('label1');
console.log(label1.mycustomattribute);
// > "Hi there."
};