如何使用React多次添加相同的CSS属性(例如background-image)? [英] How do I add the same CSS property (e.g. background-image) multiple times with React?
问题描述
我想做等价于 style =" quotbackground-image:url(foo.jpg);的内容.背景图片:React组件中的-webkit-image-set(url(foo_1x.jpg)1x,url(foo_2x.jpg)2x)"
.
React要求我提供一个样式对象,而不是字符串.但是JS对象不能具有相同的属性两次.
React requires me to provide a style object, not a string. But a JS object can't have the same property twice.
如何获得两个 background-image
属性?而且,顺序很重要–图像集必须在最后.
How do I get two background-image
properties? Also, the order is significant – the image-set needs to be last.
它必须是内联样式.(因为URL是从DB检索到的动态的内插值.)
It needs to be an inline style. (Because the URL is a dynamic, interpolated value retrieved from DB.)
推荐答案
"spassvogel"在GitHub上有一个使用CSS变量的聪明解决方案: https://github.com/facebook/react/issues/20757#issuecomment-776191029
"spassvogel" on GitHub has a clever solution using CSS variables: https://github.com/facebook/react/issues/20757#issuecomment-776191029
想法是在 style
属性中设置CSS变量,例如
The idea is to set CSS variables in the style
property, like
style={ "--url1": "url(1.jpg)", "--url2": "url(2.jpg)" }
,然后从外部样式表中使用它们,例如
and then using them from an external style sheet, like
background-image: var(--url1);
以此类推.
Turns out this still wasn't enough to solve everything I wanted – this rabbit hole runs ever deeper – but that's no fault of React's, so I'll consider this a valid answer.
这篇关于如何使用React多次添加相同的CSS属性(例如background-image)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!