【问题标题】:Background Image won't show in React component背景图像不会显示在 React 组件中
【发布时间】:2020-04-16 20:33:52
【问题描述】:

我正在创建一个简单的 React 应用(使用 create react app 作为起点),其中 App.js 返回以下内容:

  return (
    <div className="App">
      <NavBar />
      <Main />
    </div>
  );
}

export default App;

我正在尝试使用以下内容将图像添加到 Main:

  return (
    <div className="bg">      
      <LogInSignUpModal />
    </div>
  );
}

export default Main;

在 Main.css 文件中,我有以下内容:

    /* The image used */
    background-image:  url("../../images/WorkoutRack.jpg");

    /* Full height */
    height: 100%;
    width: 100%;

    /* Center and scale the image nicely */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }

不幸的是,图像不会出现在主组件中(主组件应该占据 NavBar 下方的整个页面。我尝试了在其他 StackOverflow 响应中找到的许多不同解决方案,但没有一个有效。我是什么这里不见了?

【问题讨论】:

  • 确保包裹这个bg元素的所有元素的高度设置为100%。这包括htmlbody#root。打开开发控制台,包装此bg 元素的任何元素都应设置为height: 100%;
  • 尝试 background 而不是 background-image
  • @MattCarlotta 谢谢 - 这似乎奏效了!我将 index.html(具有#root)存储在公用文件夹中,而所有组件都存储在 src 文件夹中。哪个最适合#root:在外部导入的 CSS 文件 中设置高度 100% 还是在 index.html 中设置?
  • @DanielS。很高兴你想出来了。您应该在外部 CSS 样式表中设置高度 - 使您的 index.html 尽可能干净。如果你想知道为什么会这样,简单来说,未定义高度和宽度的父元素是 0px x 0px。因此,当孩子设置为 100%(高度或宽度)时……它是 0px 的 100%。这就是为什么您必须遍历 DOM 树并将所有父元素设置为视图的 100% 的原因——除非您在 px/em/rem...等中定义高度/宽度,那么您只需要设置最近的父级的样式)。

标签: css reactjs components


【解决方案1】:

您好,我们可以在反应组件本身中以几种方式加载图像

import react from 'react'
import imageName from './location/of/image'

class App extends react.Component{
render(){
return(
<img src={imageName} alt="imagename"/>
}
}

第二种方法是使用 require 所有代码都相似,但不是导入,而是需要它

import react from 'react'
Const imageName = require ('./location/of/image')

class App extends react.Component{
render(){
return(
<img src={imageName} alt="imagename"/>
}
}

【讨论】:

    【解决方案2】:

    首先检查这个答案: React won't load local images 如果这不是问题,请检查您的父样式或使用 px 作为 with 和 height。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 2017-06-25
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多