0

找不到一个清晰的例子,如何在 .css 对象中使用函数styled-components。它不会引发错误,但在提取道具时不会将背景添加到 CSS 输出中,如下例所示。

// Simple color function
const color = (error) => {
 if (error) {
   return 'red'
 }
 return 'black',
}

作品- css

const StyledInput = styled.input<InputProps>`
  background: ${({ error }) => color(error)};`;

工作- css 对象

const StyledInput = styled.input<InputProps>(props => ({
  background: color(), // !!! NEED error from props
}));

不工作- css 对象

const StyledInput = styled.input<InputProps>(props => ({
  background: `${({ error }) => color(error)}`,
}));
4

1 回答 1

1

要解决道具提取问题,您应该能够这样做:

// Simple color function
const color = (error) => {
  if (error) {
    return 'red';
  }
  return 'black';
};

const StyledInput = styled.input<InputProps>(({ error, ...props }) => ({
  background: color(error),
}));
于 2020-04-01T16:20:05.250 回答