2016-06-08 38 views
0

我遇到NativeScript 2.0 CSS和自定義組件的問題。我的知識似乎存在巨大差距,我錯過了一些非顯而易見的重要事項。NativeScript 2.0自定義組件和CSS

,要考慮與

$ tns create test --ng 

創建了一個空NS 2.0應用刪除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。

我哪裏錯了?

回答

3

我在給定的代碼片段中檢查了您的代碼,發現它可能是NativeScript問題。目前,使用內聯樣式更改CustomViewStackLayout的寬度僅適用於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"; 

} 

應用。css

.customViewStyle{ 
    width:80%; 
} 
+0

我剛查過Android。你是對的;工作正常。不幸的是,即使使用CSS樣式(仍然適用於Android),我無法讓iOS進行更改。感謝您的洞察力 – Wainage

+0

對於延遲迴復,我感到抱歉。我做了一些研究並編輯了上面的答案。這個問題的可能的解決方法可能是綁定'cssClass'屬性並設置類名稱。我在'iOS'和'Android'上測試了它,並且它在兩個平臺上都能正常工作。 –