How do I add the same CSS property (e.g. background-image) multiple times with React?

試著忘記壹切 提交于 2021-02-09 07:25:16

问题


I want to do the equivalent of style="background-image: url(foo.jpg); background-image: -webkit-image-set(url(foo_1x.jpg) 1x, url(foo_2x.jpg) 2x)" in a React component.

React requires me to provide a style object, not a string. But a JS object can't have the same property twice.

How do I get two background-image properties? Also, the order is significant – the image-set needs to be last.

It needs to be an inline style. (Because the URL is a dynamic, interpolated value retrieved from DB.)


回答1:


I think I initially misunderstood your question. Seems you are looking to create a style object to pass as a prop to a component. You can combine your background images into a single comma separated list. You can use a string template to inject the dynamic image urls at runtime.

const style = {
  backgroundImage: `url(${url1}),-webkit-image-set(url(${url2}) 1x, url(${url3}) 2x)`,
};


来源:https://stackoverflow.com/questions/66060349/how-do-i-add-the-same-css-property-e-g-background-image-multiple-times-with-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!