2017-07-18 65 views
0

我創建了一個正在採用數組並將所有進度條堆疊成一個的反應組件。從反應循環中獲取索引值並將其傳遞給css

const ProgressBar = (props, {...customProps}) => { 

    const GroupProgressBar = []; 
    props.groups.map((group, i) => { 

     const widthValue = (group.value/group.max) * 100; 

     GroupProgressBar.push 

     (<div style={{width: `${widthValue}%`}} 
     key = {i} 

     className={`well-background--${group.concept} 
        animation 
        terra-ProgressGroup--progress 
        terra-ProgressBar--${props.heightSize}`}> 

     </div>); 
    }) 

    return <div className='terra-ProgressGroup'> {GroupProgressBar} </div> 
} 

CSS(以下班我要轉換爲單班):

....

.well-background--concept1 { 
    animation-delay: 1s; 
    z-index: -1; 
} 
.well-background--concept2 { 
    animation-delay: 2s; 
    z-index: -2; 
} 
.well-background--concept3 { 
    animation-delay: 3s; 
    z-index: -3; 
} 

我想這些類轉換成一個,但有沒有運氣

:root { 
    --concept-code: key; 
    --concept-code2: key; 
} 

.animation { 
    animation-delay: var(--concept-code)s; 
    z-index: var(--concept-code2); 
} 

基本上我不想繼續添加那些類似的類,所以我試圖創建一個類並傳遞thos來自反應組分的電子號碼。可能使用key = {i}

我該如何做到這一點?

回答

0

爲什麼在這種情況下甚至會因爲CSS而煩惱? CSS的要點是風格級聯並具有層次結構。如果該樣式僅適用於特定的React組件,則最好直接渲染適當的樣式。

const ProgressBar = (props, {...customProps}) => { 

    const GroupProgressBar = []; 
    props.groups.map((group, i) => { 

     const widthValue = (group.value/group.max) * 100; 

     GroupProgressBar.push 

     (<div 
     style={{ 
      width: `${widthValue}%`, 
      animationDelay: /* based on the concept number */, 
      zIndex: /* based on the concept number */ 
     }} 
     key = {i} 

     className={`well-background--${group.concept} 
        animation 
        terra-ProgressGroup--progress 
        terra-ProgressBar--${props.heightSize}`}> 

     </div>); 
    }) 

    return <div className='terra-ProgressGroup'> {GroupProgressBar} </div> 
} 

請注意,我不知道如何爲您的樣式生成適當的數字,因爲我不知道您的數據結構。但那將是微不足道的。重要的部分只是在組件中呈現樣式而不是CSS。

使用React動態注入CSS類樣式定義到頁面並不是一個好方法。即便如此,這將大大過度設計解決這個問題的解決方案。更好的辦法是手動在CSS中創建大量的.well-background類定義,就像你認爲你需要的那樣多(10-20個,實際上會有多少個)。

+0

感謝您的回答。我是新來的反應。我怎麼能從字符串中提取數字值?字符串將像concept1,concept2等。我在className中以group.concept的形式訪問它。團體是一個概念和價值的數組。 – User7354632781

+0

嘗試了一些東西。我如何在我的組件中實現這一點。 ''const constDelay = group.concept.match(/ \ d/g); animationDelay = animationDelay.join(「」);'' – User7354632781

+0

我試圖實現它。得到這個'''警告:一個'div'標籤(owner:'ProgressBar')被傳入一個CSS屬性'animationDelay'(value:'1')的數字字符串值,在未來的版本中將被視爲無單位數字React.''' – User7354632781

相關問題