NativeScript 2.0自定义组件和CSS

时间:2016-06-08 17:13:08

标签: nativescript angular2-nativescript

我遇到了NativeScript 2.0 CSS和自定义组件的问题。我的知识似乎存在巨大差距,而且我错过了一些非显而易见的重要内容。

使用

创建一个空的NS 2.0应用程序
$ tns create test --ng

删除 app.css 的内容(以防止副作用)。

更改 app.component.ts

import {Component} from "@angular/core";

@Component({
    selector: "my-app",
    template: `
    <StackLayout orientation="vertical">
        <Label text="Label in first StackLayout"></Label>
        <StackLayout orientation="vertical" 
                     style="width: 80%;background-color: red;">
            <Label text="Label in second StackLayout"></Label>
        </StackLayout>
    </StackLayout>
    `,

})
export class AppComponent {}

非常基本的东西。生成以下预期结果:

Expected result

让我们尝试将内部StackLayout转换为可重用的组件。

custom.component.ts

import {Component} from "@angular/core";

@Component({
    selector: "Custom",
    template: `
    <StackLayout orientation="vertical" 
                 style="width: 80%;background-color: red;">
        <Label text="Label in second StackLayout"></Label>
    </StackLayout>
    `,

})
export class CustomComponent {}

更改 app.component.ts

import {Component} from "@angular/core";
import {CustomComponent} from "./custom.component"

@Component({
    selector: "my-app",
    directives: [CustomComponent],
    template: `
    <StackLayout orientation="vertical">
        <Label text="Label in first StackLayout"></Label>
        <Custom></Custom>
    </StackLayout>
    `,

})
export class AppComponent {}

现在输出如下:

enter image description here

应用背景颜色但宽度不是。

我甚至尝试过:

<Custom style="width: 80%;"></Custom>  /* Does this even make sense? */

无济于事。

我意识到百分比是experimental,但怀疑错误是在我的代码而不是NativeScript中。

我哪里出错了?

1 个答案:

答案 0 :(得分:3)

我在给定的代码段中查看了您的代码,发现它可能是NativeScript问题。目前,使用内联样式更改StackLayoutCustomView的宽度仅适用于Android。要在两个平台上使用%更改CustomView的宽度,您应该在css文件中设置此属性并绑定cssClass属性。

<强> custom.component.ts

import {Component} from "@angular/core";

@Component({
    selector: "Custom",
    template: `
    <StackLayout orientation="vertical" 
                 [cssClass]="styleView" style="background-color: red;">
        <Label text="Label in second StackLayout"></Label>
    </StackLayout>
    `,

})
export class CustomComponent {

      public styleView="customViewStyle";

}

<强> app.css

.customViewStyle{
    width:80%;
}
相关问题