Making Styled Components DRYer

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 04:59:00

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/56654462/making-styled-components-dryer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!