根据数组设置偶数或奇数的背景颜色 - ReactJS
Set background color on even or odd based on array - ReactJS
我正在尝试根据页面上的部分设置不同的背景。
console.log(currentPage.sections)
// Array(10)
据此我猜测哪个数字是奇数哪个不是
const isItOdd = currentPage?.sections.map((section, i) => i % 2)
// output : [ 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 ]
除此之外,我还将数据提供给 styled-component
,以便我可以根据需要更改背景
<Container isOdd={isItOdd}>
此外,我将我的组件设计成这样
export const Container = styled.div<{ isOdd?: number[] }>`
background: ${({ isOdd }) => (isOdd ? 'salmon' : 'white')};
`
但不幸的是我没有得到我需要的结果。显示的唯一颜色是 salmon
。那我做错了什么?
有人可以解释一下吗?
编辑:我想要的最终结果是这样的:
正如@Brian Thompson 所建议的那样。我们应该更深入地研究以解决此问题。 CSS pseudo-class
至少这对我有用并解决了我的问题。
正如他提到的,我当前显示颜色的数组不正确。
因为我正在检查一个数组。并且数组始终具有真实值。
这里的答案是使用 psuedo 类 并根据它们渲染我们想要的颜色
import { css } from '@emotion/core'
export const Container = styled.div<{ isOdd?: number[] }>`
${({ isOdd }) =>
isOdd &&
css`
&:nth-child(even) {
background: salmon;
}
&:nth-child(odd) {
background: white;
}
`}
`
我正在尝试根据页面上的部分设置不同的背景。
console.log(currentPage.sections)
// Array(10)
据此我猜测哪个数字是奇数哪个不是
const isItOdd = currentPage?.sections.map((section, i) => i % 2)
// output : [ 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 ]
除此之外,我还将数据提供给 styled-component
,以便我可以根据需要更改背景
<Container isOdd={isItOdd}>
此外,我将我的组件设计成这样
export const Container = styled.div<{ isOdd?: number[] }>`
background: ${({ isOdd }) => (isOdd ? 'salmon' : 'white')};
`
但不幸的是我没有得到我需要的结果。显示的唯一颜色是 salmon
。那我做错了什么?
有人可以解释一下吗?
编辑:我想要的最终结果是这样的:
正如@Brian Thompson 所建议的那样。我们应该更深入地研究以解决此问题。 CSS pseudo-class
至少这对我有用并解决了我的问题。 正如他提到的,我当前显示颜色的数组不正确。 因为我正在检查一个数组。并且数组始终具有真实值。
这里的答案是使用 psuedo 类 并根据它们渲染我们想要的颜色
import { css } from '@emotion/core'
export const Container = styled.div<{ isOdd?: number[] }>`
${({ isOdd }) =>
isOdd &&
css`
&:nth-child(even) {
background: salmon;
}
&:nth-child(odd) {
background: white;
}
`}
`