Javascript 使用样式在 React.js 中设置背景
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36413862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set background in React.js using style
提问by Marcel
I want to add a background image in React.js by using a style definition, which works:
我想通过使用样式定义在 React.js 中添加背景图像,该样式定义有效:
let imgUrl = 'images/berlin.jpg'
let styles = {
root: {
backgroundImage: 'url(' + imgUrl + ')',
overflow: 'hidden',
},
...
As you can see, the image repeats in x-direction. So I wanted to extend it by:
如您所见,图像在 x 方向重复。所以我想通过以下方式扩展它:
let imgUrl = 'images/berlin.jpg'
let styles = {
root: {
backgroundImage: 'url(' + imgUrl + ')',
backgroundImage: {
flex: 1,
resizeMode: 'cover', // or 'stretch'
},
overflow: 'hidden',
},
...
But the image is not loaded anymore:
但图像不再加载:
So how to set the background image and adjust it in React.js?
那么如何在 React.js 中设置背景图片并进行调整呢?
回答by Marcel
回答by Rodrigo Cipriani da Rosa
Clarifing another answer
澄清另一个答案
let imgUrl = 'images/berlin.jpg'
let styles = {
root: {
backgroundImage: `url(${ imgUrl })`
backgroundRepeat : 'no-repeat',
backgroundPosition: 'center',
}
}
回答by Erik Martín Jordán
If you use an image as background, is better to use the 'backgroundImage' property.
如果您使用图像作为背景,最好使用 'backgroundImage' 属性。
If you use the 'background' property, this may cause issues on reloading the component (e.g. 'cover' attribute will not apply properly).
如果您使用 'background' 属性,这可能会导致重新加载组件时出现问题(例如,'cover' 属性将无法正确应用)。
Solution proposed:
提出的解决方案:
let imgUrl = 'images/berlin.jpg';
<div className = 'Component-Bg'
style = {{ backgroundImage: `url(${imgUrl})`,
backgroundSize: 'cover',
backgroundPosition: 'center center',
backgroundRepeat: 'no-repeat',
}}>
</div>
回答by FLCcrakers
Have you tried somthing like this :?
你有没有尝试过这样的事情:?
let imgUrl = 'images/berlin.jpg'
let styles = {
root: {
background: 'url('+ imgUrl + ') noRepeat center center fixed',
backgroundSize: 'cover',
}
Inspired from this post: Stretch and scale a CSS image in the background - with CSS only
灵感来自这篇文章:在背景中拉伸和缩放 CSS 图像 - 仅使用 CSS