【问题标题】:Passing props along from styled component using Emotion.sh使用 Emotion.sh 从样式化组件传递道具
【发布时间】:2020-05-26 19:59:06
【问题描述】:

我使用@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 =&gt; props.width

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

【问题讨论】:

    标签: javascript styled-components emotion


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-10-28
      • 2019-11-11
      • 2019-09-23
      • 2021-06-29
      • 1970-01-01
      • 2017-08-17
      • 2021-01-13
      • 2022-11-15
      • 2023-01-04
      相关资源
      最近更新 更多