从 ObservableArray 中的数据设置 CSS class

Setting CSS class from data in ObservableArray

我有一个包含一些信息的可观察数组。我希望根据数组中包含的数据动态更改 class。我试过:

#js
var pageData = new Observable({
    locations: new ObservableArray([
        {location: 'OR1'},
        {location: 'OR2'},
        {location: 'OR3'},
        {location: 'WR1'},
        {location: 'PO1'}
     ]),
     surgeons: new ObservableArray([
        {surgeon: 'Dr. Pepper', selected_text: '', selected_class: ''},
        {surgeon: 'Dr. Scholls', selected_text: "\uf111", selected_class: 'font-awesome'}
    ])
    });

exports.loaded = function(args) {
    var page = args.object;
    page.bindingContext = pageData;
};


#xml
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="onNavigatingTo" xmlns:statusBar="nativescript-statusbar"
  class="green" loaded="loaded">
<GridLayout orientation="vertical" columns="*" rows="2*,*,3*,*,5*,*">
    <Label text="mrn: 123456" row="0" class="h1" horizontalAlignment="center"/>
    <Label text="Surgeon"  class="h3" row="1"/>
    <ListView col="0" row="2" items="{{ surgeons }}" separatorColor="#58847D" class="margin-sides-10 rounded-corners-all">
        <ListView.itemTemplate>
            <GridLayout orientation="vertical" columns="75,*" rows="*">
                <Label text="{{ selected_text }}" class="{{ selected_class}} black-text" col="0"/>
                <Label text="{{ surgeon }}" class="black-text" col="1"/>
            </GridLayout>
        </ListView.itemTemplate>
    </ListView>
    <Label text="Location"  class="h3" row="3"/>
    <ListView col="0" row="4" items="{{ locations }}" separatorColor="#58847D" class="margin-sides-10 rounded-corners-all">
        <ListView.itemTemplate>
            <Label text="{{ location }}" class="black-text"/>
        </ListView.itemTemplate>
    </ListView>

    <Button text="Save" class="dark-grey margin-top-10" row="5" tap="save"/>

</GridLayout>

有条件地设置单个组件样式的最佳方法是什么?

实际上它不起作用的原因是你的 XML 中有一个简单的错误。您的 xml 需要:

<Label text="{{ selected_text }}" class="{{selected_class}}" col="0"/>

您不能在同一个元素中混合使用可观察代码和不可观察代码属性。通过将 "black-text" 添加到 class 属性;那么 NativeScript 会将其视为名为 .{{selected_class}} 和 .black-text 的文字 class。