首页 > 解决方案 > 使用 Emotion.sh 从样式化组件传递道具

问题描述

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

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

在我的代码中,size是一个基于传递的道具返回大小 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 ie 的解析值s,而是一个 string props => props.width

有没有办法将道具从类似于我想要实现的样式组件传递到函数中?

标签: javascriptstyled-componentsemotion

解决方案


它不起作用,因为您将匿名函数传递给width, 在您不期望函数的地方。

我很确定这是你想要做的:

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

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


推荐阅读