【问题标题】:How would an alternate color pass every 4 elements to repeat the same component pattern with Array.map function?替代颜色如何通过每 4 个元素通过 Array.map 函数重复相同的组件模式?
【发布时间】:2022-01-18 19:10:12
【问题描述】:

我正在尝试向反应应用程序中的子组件发送一种替代颜色作为属性,但我不确定该怎么做。每个CardSimpleRow 组件的颜色必须以4 种不同的颜色交替,一旦出现第4 种颜色,它就会返回到颜色的开头,比如说。我想使用 map,因为我的矩阵是动态的,并且编写矩阵的每一行来渲染似乎是不必要的。

export const FollowScreen = () => {
  const alternatingColor = [ ["#d72226", "#a8232a"], ["#123", "#a33a"], ["#f3f3f3", "#a8232a"], ["#dd26", "#a8232a"] ]
  return (
   <>
     {
       data.map((elements, index) => {
          return  <CardSimpleRow 
                     color={index % 4 ? alternatingColor[1] : alternatingColor[0]} 
                     elements={elements} 
                  />
       })
     }
   </>

  )

这是一个渐变,所以我需要发送第一个数组,然后是第二个数组,然后是第三个,然后是第四个,然后返回到第一个数组>

例如如果有 8 个CardSimpleRow,我需要 4 张卡片,数组从 0 到 4,然后再另外四张,数组从 0 到 4

【问题讨论】:

    标签: css reactjs react-native colors


    【解决方案1】:

    如果我猜对了,你需要这样的东西:

    alternatingColor[0]
    alternatingColor[1]
    alternatingColor[2]
    alternatingColor[4]
    alternatingColor[0]
    alternatingColor[1]
    ...
    

    要获得,您只需要更改一行:

    ...
    color={alternatingColor[index % 4]} 
    ...
    

    这将通过获取基于索引的整数余数来访问alternatingColor 中的正确元素。

    索引 0 => 0 / 4 的余数 == 0
    索引 1 => 1 / 4 的余数 == 1
    ...
    索引 5 => 5 / 4 的余数 == 1

    【讨论】:

    • 你太棒了,非常感谢兄弟!
    猜你喜欢
    • 2013-07-22
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 2018-06-25
    • 2019-12-28
    相关资源
    最近更新 更多