如何从 graphQl 查询中获取变量到内联样式或样式组件中的伪元素

IT技术 css reactjs gatsby pseudo-element styled-components
2021-05-21 10:30:52

我有一个难题我似乎无法解决我正在从 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;
  }
`

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

更新尝试

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;
}
1个回答

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

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;
  }
`

然后像使用颜色props的普通组件一样使用它:

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