使用Emotion.sh从样式组件传递道具

时间:2020-02-11 12:03:44

标签: javascript styled-components emotion

我使用@emotion\styled声明了以下样式的按钮:

const Button = styled.button`
 background: blue;
 ${size({
  width: props => props.width
 )}
`

在我的代码中,size是一个基于所传递的prop返回大小css序列化样式的函数:


const size = ({ width: "m"} = {}) => {
 switch(width) {
  case "s":
   return css`width: 100px`;
  break;
  case "m":
   return css`width: 150px`;
  break;
 }
} 
<Button width="s">Some text</Button>

但是,我在width函数中收到的size值不是传递的prop的解析值,即s,而是一个字符串props => props.width

有什么方法可以将道具从样式化组件传递到功能中,就像我想要实现的那样?

1 个答案:

答案 0 :(得分:1)

由于您要在不希望使用函数的地方将匿名函数传递给width,因此该方法不起作用。

我很确定这是您要尝试执行的操作:

const Button = styled.button`
 background: blue;
 ${props => size({ width: props.width })}
`

这样,您将在样式声明的范围内传递一个匿名函数,从Emotion获取道具,并可以随意使用它。