javascript - 使用 Emotion.sh 从样式组件传递 Prop

标签 javascript styled-components emotion

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

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

在我的代码中,size 是一个函数,它根据传递的 prop 返回 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>

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

有什么方法可以将 Prop 从类似于我想要实现的样式组件传递到函数中吗?

最佳答案

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

我很确定这就是您想要做的:

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

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

关于javascript - 使用 Emotion.sh 从样式组件传递 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60168380/

相关文章:

Javascript - 在继续之前等待事件

javascript - 访问包含函数

javascript - 由于缺少绿色灯泡,无法在 Visual Studio 中自动创建 jsconfig.json

reactjs - 如何在 React.JS 中添加 ClassName 并删除 onScroll 事件?

php - Drupal - 我正在尝试使用 Fivestar 模块投票后刷新 View

reactjs - styleOverrides 未应用于 MUI 中的样式组件

reactjs - React 样式组件淡入/淡出

reactjs - 嵌套情感 10 个级联类

css - 使用 Chakra UI 时如何覆盖自动填充输入的样式?

reactjs - React Emotion 是否支持::before/::after 选择器?