从反应循环中获取索引值并将其传递给css

问题描述:

我创建了一个正在采用数组并将所有进度条堆叠成一个的反应组件。从反应循环中获取索引值并将其传递给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}

我该如何做到这一点?

为什么在这种情况下甚至会因为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