Styled-Components,如何动态生成css属性?
Styled-Components, how to dynamically generate css properties?
给定两个动态属性:
- 当前颜色
- 剩余卡片
和const colors = ['blue', 'red', 'green', 'yellow', 'orange']
使用 Styled 组件,如何动态设置 box-shadow 属性?其中,数字 cardsRemaining 指定框阴影值的数量。
例如,cardsRemaining == 2:
box-shadow:
8px 0 0 0 colors[current+1],
16px 0 0 0 colors[current+2];
例如,cardsRemaining == 4:
box-shadow:
8px 0 0 0 colors[current+1],
16px 0 0 0 colors[current+2],
24px 0 0 0 colors[current+3],
32px 0 0 0 colors[current+4];
其中 currentColor
用于分配每个 box-shadow 值中的颜色。
所以如果 cardsRemaining == 4 && currentColor == blue:
box-shadow:
8px 0 0 0 red,
16px 0 0 0 green,
24px 0 0 0 yellow,
32px 0 0 0 orange;
或者,如果 cardsRemaining == 2 && currentColor == yellow:
box-shadow:
8px 0 0 0 orange,
16px 0 0 0 blue;
您将如何使用样式化组件解决此类问题?
谢谢
在样式组件中,可以访问道具。因此,您可以执行以下操作 -
export getBoxShadow = ({cardsRemaining, currentColor }) => logicHere
export const StyledComponent = styled.div`box-shadow: ${getBoxShadow};`
来自@OwlyMoly 的编辑:如果您只想传递颜色:
const StyledComponent = styled.div`
box-shadow: 8px 0 0 0 ${props => props.colorToBe}
`
您可以编写一个函数,将 return 给定属性作为参数的样式。
给你:solution
给定两个动态属性:
- 当前颜色
- 剩余卡片
和const colors = ['blue', 'red', 'green', 'yellow', 'orange']
使用 Styled 组件,如何动态设置 box-shadow 属性?其中,数字 cardsRemaining 指定框阴影值的数量。
例如,cardsRemaining == 2:
box-shadow:
8px 0 0 0 colors[current+1],
16px 0 0 0 colors[current+2];
例如,cardsRemaining == 4:
box-shadow:
8px 0 0 0 colors[current+1],
16px 0 0 0 colors[current+2],
24px 0 0 0 colors[current+3],
32px 0 0 0 colors[current+4];
其中 currentColor
用于分配每个 box-shadow 值中的颜色。
所以如果 cardsRemaining == 4 && currentColor == blue:
box-shadow:
8px 0 0 0 red,
16px 0 0 0 green,
24px 0 0 0 yellow,
32px 0 0 0 orange;
或者,如果 cardsRemaining == 2 && currentColor == yellow:
box-shadow:
8px 0 0 0 orange,
16px 0 0 0 blue;
您将如何使用样式化组件解决此类问题?
谢谢
在样式组件中,可以访问道具。因此,您可以执行以下操作 -
export getBoxShadow = ({cardsRemaining, currentColor }) => logicHere
export const StyledComponent = styled.div`box-shadow: ${getBoxShadow};`
来自@OwlyMoly 的编辑:如果您只想传递颜色:
const StyledComponent = styled.div`
box-shadow: 8px 0 0 0 ${props => props.colorToBe}
`
您可以编写一个函数,将 return 给定属性作为参数的样式。 给你:solution