通过函数或变量设置背景图像

时间:2015-09-08 12:16:27

标签: css reactjs

我试图根据React组件中的各种情况更改div的背景图像,但首先我需要弄清楚是否可以通过变量或函数设置背景图像,它似乎不可能。例如,对于变量,像这样的伪代码似乎不起作用

render: function(){
var myvariable = "url('http://localhost:8080/assets/myimage.jpg')"
return (
    <div style={{ "backgroundImage": { myvariable }, "width": "300px"}}</div>
     )
}

我也尝试从内联样式调用函数,但编译器在.

中反对this.setBackgroundImage {}}
 setBackgroundImage: function(){
     return "url('http://localhost:8080/assets/myimage.jpg')"
 },
 render: function(){

    return (
        <div style={{ "backgroundImage": { this.setBackgroundImage }, "width": "300px"}}</div>
         )
    }

问题:是否可以调用函数或在React中使用内联样式中的变量,如果没有,我怎样才能实现我尝试做的事情(即为div旋转背景图像)? / p>

注意,div必须有其他样式(宽度,高度等),而不仅仅是背景图像

1 个答案:

答案 0 :(得分:1)

基本上你需要做的是编写样式:

var divStyle = {
  backgroundImage: 'url(' + imgUrl + ')',
  width: '300px'
};

然后使用它们内联:

return (
  <div style={divStyle}></div>
)

React Inline Styles