2016-10-06 25 views
0

我創建了一個簡單的組件來渲染來自SVG sprite的圖標。這個組件應該有一個默認的CSS類來全局管理它的樣式(.svg-icon)。另外,我想通過'class'屬性通過類名添加一些依賴於上下文的樣式。Ember 1.13,組件中的類名稱順序

JS:

App.SvgIconComponent = Ember.Component.extend 
    layoutName: 'components/svg-icon' 
    classNames: ['svg-icon'] 
    tagName: 'svg' 
    attributeBindings: ['width', 'height', 'fill'], 

    width: 16 
    height: 16 
    fill: 'currentColor' 

模板:

<use xlink:href="#svg-icon-{{name}}"/> 

用法:

{{svg-icon name="facebook" class="social__icon" width="14" height="14"}} 

HTML輸出:

<svg id="ember1012" width="14" height="14" fill="currentColor" class="social__icon ember-view svg-icon"> 
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#svg-icon-facebook"></use> 
</svg> 

問題是,Ember將我的默認類(.svg-icon)推入類列表的末尾。但是,爲了避免級聯的一些問題,我需要在課程開始時列出這個類(class =「svg-icon social__icon ember-view」)。是否有可能實現?

我知道,我可以用classNameBindings屬性設置類名,但在這種情況下,我需要使用一些與'class'不同的屬性。使用原生'class'屬性是更可取的。

Thnx。

+1

是否爲了類別在SVG班級列表此事界定?它[不在其他HTML元素上](http://stackoverflow.com/a/8127373/557612)。 – steveax

+0

@steveax哈,我確定這很重要,但事實並非如此!所以我的問題沒有更多的意義。 thnx回覆。 – Kuzzy

回答

1

試試這個,

{{svg-icon name="facebook" classNames="social__icon" width="14" height="14"}} 

上述工作,但它沒有使用類屬性。所以它不符合你的要求。

但如果這不符合您的要求,您可以嘗試在init方法中手動設置classNames。

init(){ 
    this._super(...arguments); 
    console.log(' Classess ',this.get('classNames')); //You will get classNames, you can do rearrange the classNames array 
    this.get('classNames').unshiftObject('svg-icon'); //to force svg-icon to be first in classNames array.  
    } 

UPDATE1

以上的init()將無法工作。所以我相信classNames值被添加到最後。首先使用本地class不可能AFAIK。但隨後你需要

我知道,我可以設置與classNameBindings屬性類的名字,但在這種情況下,我將需要使用一些屬性從「類」不同

可以提不同特定屬性的類名稱爲true。

{{my-component is_social__icon=false }} 

和內部my-component.js

classNameBindings:['is_social__icon:social__icon'] 

UPDATE2
1)您也可以太classNameBindings

export default Ember.Component.extend({ 
    classNameBindings: ['isEnabled:enabled:disabled'], 
    isEnabled: false 
}); 

isEnabled指定true和false值類的名稱 - 真 - 再它將包括enabled類n ame isEnabled - false - 那麼它將包含disabled類名

2)您甚至可以指定只爲虛假值添加類名。

classNameBindings: ['isEnabled::disabled'], 

3)可以指定多個屬性

classNameBindings:['isSocialIcon':'social__icon','isActive':'selected'] 

可以爲isSocialIconisActive屬性給組件提供值。

{{my-component isSocialIcon=true isActive=(unless social.inactive) }} 

如果isActive被解析成真,那麼它將增加social__icon selected類我的分量。

參考:https://guides.emberjs.com/v1.13.0/components/customizing-a-components-element/#toc_customizing-class-names

+0

使用init鉤子的解決方案不起作用,this.get('classNames')返回一個沒有在模板中添加類的類的數組,它只包含'ember-view'類...並且生成的HTML是:class =「my_custom_class_from查看svg-icon支持查看「。 – Kuzzy

+0

感謝您的更新,但我希望避免使用額外的屬性,特別是對布爾值的值,它使組件更復雜,難以重用。主要想法是隻保留原始SVG標籤(寬度,高度,填充和類)等屬性,設計師和HTML人員對已知屬性感覺比習慣感更舒適。 – Kuzzy

+0

如果使用classNames屬性,可以保存類的順序,但是當我需要動態添加類名時,我也遇到了問題: class =(concat'social__icon'(除非選擇'social.inactive')) - 工作好,但:classNames =(concat'social__icon'(除非選擇social.inactive'))不起作用 – Kuzzy