2016-06-08 55 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'上测试了它,并且它在两个平台上都能正常工作。 –