本文介绍了如何从 graphQl 查询中获取变量到内联样式或样式组件中的伪元素中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a bit of a condrum I can't seem to solve I am querying colors from a graphQL database from DatoCMS and want to change the color of a Pseudo element in my Gatsby js appI can do so just fine like this with a regular selector

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

但是我不知道如何引入像 :after 这样的 sudo 选择器.

However I am not sure how to introduce sudo selector like :after into the mix.

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

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

I have thought maybe styled components and This works, however I then Can't add my variables because styled components seems to live outside there scope before my loop and react component.

更新尝试

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 中收到以下错误

I get the following error in my rendered css

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

推荐答案

您可以使用 样式化的组件通过 props 来传递这样的 props:

You can use styled components passed props to pass props like this:

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

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

and then use it like normal component with a color prop:

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

这篇关于如何从 graphQl 查询中获取变量到内联样式或样式组件中的伪元素中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 06:19