首页 > 解决方案 > 如何将graphQl查询中的变量转换为内联样式或样式组件中的伪元素

问题描述

我有一点我似乎无法解决的难题我正在从 DatoCMS 的 graphQL 数据库中查询颜色,并想更改我的 Gatsby js 应用程序中伪元素的颜色我可以像这样使用常规选择器

<p style={{color: pricing.packageBorderColor.hex}} className="price-session">
   <span>${pricing.priceAmount}</span> | <span>{pricing.lengthOfSession}</span>
</p>

但是我不确定如何将 sudo 选择器:after引入到组合中。

const ListItem = styled.li`
  list-style-type: none;
  font-size: 20px;
  display: inline-block;
  width: 330px;
  &:before {
    content: url(data:image/svg+xml,${encodeURIComponent(renderToString(<FontAwesomeIcon icon={faCheck} />))});
    width: 20px;
    display: block;
    float: left;
    position: absolute;
    margin-left: -31px;
    color: {pricing.packageBorderColor.hex} // This is what I'd ideally like to do, but doesnt seem doable
  }
  span{
    display:block;
    float:left; 
    margin-top:3px;
  }
`

我曾想过可能样式化的组件并且这有效,但是我无法添加我的变量,因为样式化的组件似乎在我的循环和反应组件之前存在于该范围之外。

更新尝试

const CircleSave = styled.div`
  &:after{
    background: ({color}) => color
  }

`

<CircleSave color={pricing.packageBorderColor.hex} className="circle-save">
   <p>${pricing.packageSavings}</p>
   <p>savings</p>
 </CircleSave>

我在渲染的 CSS 中收到以下错误

.chrVyZ:after {
    background: ({color}) => color;
}

标签: cssreactjsgatsbypseudo-elementstyled-components

解决方案


您可以使用样式化组件传递道具来传递道具,如下所示:

const ListItem = styled.li`
  list-style-type: none;
  font-size: 20px;
  display: inline-block;
  width: 330px;
  &:before {
    content: url(data:image/svg+xml,${encodeURIComponent(renderToString(<FontAwesomeIcon icon={faCheck} />))});
    width: 20px;
    display: block;
    float: left;
    position: absolute;
    margin-left: -31px;
    color: ${({ color }) => color}; // This is what I'd ideally like to do, but doesnt seem doable
  }
  span{
    display:block;
    float:left; 
    margin-top:3px;
  }
`

然后像普通组件一样使用它并带有颜色道具:

<ListItem color={pricing.packageBorderColor.hex}/>

推荐阅读