With Styled Components and Polish how to include a function as the color?

落爺英雄遲暮 提交于 2019-12-24 19:43:06

问题


I'm using styled-components and polished for darkening/lightening the colors.

Here's what I have now working:

colors = ['#eee', '#ccc', '#ddd'];

const calcBorderColor = ({ currentPosition }) => {
  const color = colors[(currentPosition) % colors.length];
  return color;
};

const Choice = styled.button`
  border-color: ${calcBorderColor};
`;

Where I'm stuck is here:

&:hover {
    border-color: ${darken(0.1, calcBorderColor)};
}

That hover styling is error with Passed an incorrect argument to a color function, please pass a string representation of a color.

How can I use polished darken along with the calcBorderColor function?


回答1:


You are only getting the error when using the darken function because it expects a string as second argument and instead you are passing the function declaration of calcBorderColor that if you log it, you could see is this:

calcBorderColor(_ref) {
    var currentPosition = _ref.currentPosition;

    var color = colors[currentPosition % colors.length];
    return color;
}

If you:

console.log(typeof calcBorderColor);

You will get it is of type function.

This come because polished library functions are staticly typed by using Flow. And you are not getting an error in the first border-color because Styled Components is skipping to render the function declaration, probably leaving the default border-color of the button element.

So you need to pass as argument an object with the attribute currentPosition in both calls to the calcBorderColor function in order to make it usable and avoid that error.

const Choice = styled.button`
  border-color: ${calcBorderColor({currentPosition: 1})};

  &:hover {
    border-color: ${darken(0.1, calcBorderColor({ currentPosition: 0}))};
  }
`;


来源:https://stackoverflow.com/questions/51003397/with-styled-components-and-polish-how-to-include-a-function-as-the-color

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