【问题标题】:With Styled Components and Polish how to include a function as the color?使用 Styled Components 和 Polish 如何包含一个函数作为颜色?
【发布时间】:2018-12-02 20:15:33
【问题描述】:

我正在使用 styled-components 和抛光来加深/减轻颜色。

这是我现在的工作:

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

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

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

我被困在这里:

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

Passed an incorrect argument to a color function, please pass a string representation of a color. 的悬停样式错误

如何将抛光变暗与 calcBorderColor 函数一起使用?

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    您只在使用 darken 函数时收到错误,因为它需要一个字符串作为第二个参数,而您传递的是 calcBorderColor 的函数声明,如果您记录它,您会看到:

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

    如果你:

    console.log(typeof calcBorderColor);
    

    你会得到它的类型是function

    这是因为polished 库函数是使用Flow 静态类型化的。而且您在第一个border-color 中没有收到错误,因为样式化组件正在跳过呈现函数声明,可能会保留按钮元素的默认border-color

    因此,您需要在对 calcBorderColor 函数的两次调用中将具有属性 currentPosition 的对象作为参数传递,以使其可用并避免该错误。

    const Choice = styled.button`
      border-color: ${calcBorderColor({currentPosition: 1})};
    
      &:hover {
        border-color: ${darken(0.1, calcBorderColor({ currentPosition: 0}))};
      }
    `;
    

    【讨论】:

      猜你喜欢
      • 2018-12-02
      • 2019-11-03
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 2021-01-09
      • 2018-03-18
      相关资源
      最近更新 更多