简体   繁体   English

如何将内联样式和className应用于同一元素

[英]How To Apply Inline Style and className to Same Element

I have a div that has a decently long list of styles that would look ridiculous to apply inline, however, the div takes a parameter of a background image url that will change upon updating state. 我有一个div,其中包含相当长的样式列表,看起来很荒谬地应用内联,但是div带有背景图片网址的参数,该参数会在更新状态时发生变化。

Styled inline, my element looks like this: 内联样式,我的元素看起来像这样:

      <div style={{width: 55,
                  height: 55,
                  position: 'fixed',
                  borderRadius: '50%',
                  bottom: 130,
                  zIndex: 200,
                  backgroundImage: `url(${this.state.avatar})`}}>

However, when I do this, my background image disappears completely: 但是,当我这样做时,我的背景图像完全消失了:

<div className="avatar" style={{backgroundImage: `url(${this.state.avatar})`}}>

What is the fix here? 解决办法是什么?

I created a sample project with create-react-app and used the following code, it's working for me: 我使用create-react-app创建了一个示例项目,并使用了以下代码,它对我有用:

App.js : App.js

import React, {Component} from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {avatar: 'https://www.gstatic.com/webp/gallery3/1.png'}
  }

  render() {
    return (
      <div className="avatar" style={{backgroundImage: `url(${this.state.avatar})`}}>
        something here...
      </div>
    );
  }
}

export default App;

And the App.css : App.css

.avatar {
  width: 500px;
  height: 500px;
  position: fixed;
  border-radius: 50%;
  bottom: 130px;
  z-index: 200;
}

@salman.zare 's answer is 100% correct to the question I had posted, however, the problem I had turned out not to have anything to do with combining a className and an inline style. @ salman.zare的答案对于我发布的问题是100%正确的,但是,事实证明我与组合className和内联样式没有任何关系。 The issue was that my div container was too small for the image, 50px. 问题是我的div容器太小,无法容纳50px的图片。 Here is was I added to make it work: background-size: contain; 这是我为了使其工作而添加的: background-size: contain;

So: 所以:

.avatar {
  width: 50px;
  height: 50px;
  position: fixed;
  border-radius: 50%;
  bottom: 130px;
  z-index: 200;
  background-size: contain;
}

This also works and will not cut-off the bottom of the image if using no-repeat: background-size: 100% 100%; 如果使用不重复,这也将起作用,并且不会切掉图像的底部:background-size:100%100%;

.avatar {
  width: 55px;
  height: 55px;
  position: fixed;
  border-radius: 50%;
  bottom: 130px;
  z-index: 200;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM