制作样式组件干燥器 [英] Making Styled Components DRYer
问题描述
说到在 Styled Components 中检查 props 时,在我看来,事情可能是一个很大的 DRYer.
例如,让我们看看下面的代码:
${props =>props.white &&`颜色:${colors.white}`}${道具=>props.light &&`颜色:${colors.light}`}${道具=>props.grey &&`颜色:${colors.grey.base}`}${道具=>props.dark &&`颜色:${colors.dark}`}${道具=>props.black &&`颜色:${colors.black}`}${道具=>props.info &&`颜色:${colors.info}`}${道具=>props.success &&`颜色:${colors.success}`}${道具=>props.warning &&`颜色:${colors.warning}`}${道具=>props.error &&`颜色:${colors.error}`}${道具=>props.link &&`颜色:${colors.link.base}`}
这是针对我正在创建的
组件 - 它只是根据我使用的道具检查文本颜色的变化.例如:
将赋予它light
颜色,这是我在变量文件中的 colors
对象中设置的.>
现在,这段代码相当重复.每行唯一改变的是颜色名称——否则完全相同.
关于如何使此代码干燥的任何想法?
这里的问题是,如果用户在 props 中添加 white
和 black
会发生什么?应该是什么颜色?
${props =>Object.keys(props).filter(x => colors[x]).map(y => `color: ${colors[y]}`).join(' ')}
这样,你过滤了colors
中的props,给它添加样式文本,.join
就是把数组转换成字符串.
如果只传递一个颜色的道具,它会工作,但如果传递一个以上,它会进入.map
的最后一个颜色.
When it comes to checking for props in Styled Components, it seems to me that things could be a great deal DRYer.
For instance, let's take a look at the following code:
${props => props.white && `color: ${colors.white}`}
${props => props.light && `color: ${colors.light}`}
${props => props.grey && `color: ${colors.grey.base}`}
${props => props.dark && `color: ${colors.dark}`}
${props => props.black && `color: ${colors.black}`}
${props => props.info && `color: ${colors.info}`}
${props => props.success && `color: ${colors.success}`}
${props => props.warning && `color: ${colors.warning}`}
${props => props.error && `color: ${colors.error}`}
${props => props.link && `color: ${colors.link.base}`}
This is for a <Text>
component that I'm creating - it simply checks changes the color of the text depending on which prop I use. For instance: <Text light>
will give it the light
color that I set up in my colors
object from my variables file.
Now, this code is rather repetitive. The only thing that changes on each line is the color name -- otherwise it's exactly the same.
Any ideas on how I can make this code DRYer?
The problem here is, what happens if the user adds white
and black
to the props? What color should it be?
${props => Object.keys(props).filter(x => colors[x]).map(y => `color: ${colors[y]}`).join(' ')}
This way, you are filtering the props that is in colors
, add the style text to it and .join
is to convert the array into a string.
It will work ok if only one prop that is in color is passed, but if more than one is passed, it will go in the last color of .map
.
这篇关于制作样式组件干燥器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!