【问题标题】:BackgroundImage not showing in JSX?BackgroundImage 没有在 JSX 中显示?
【发布时间】:2019-12-10 05:54:05
【问题描述】:

我正在尝试在 JSX 中加载此背景图片,但是,经过所有尝试后,图片将无法加载。

Row 组件来自 ReactStrap,我使用的是 WebPack。

我试过 backgroundColor 并且颜色渲染得很好。

我已经尝试了引号和模板文字的所有组合。

我试过不使用 <row /> 组件,而只是在常规 div 上使用样式,仍然没有运气。

我尝试过内联并在变量中的单独对象中。

我尝试过使用 ref。

png图片与js文件在同一个文件夹中。

在 Chrome 开发工具中,图像看起来就像已加载到容器中一样正常。

谁能看到我在这里做错了什么?

<Row style={{ backgroundImage: `url('./leigh.png')` }} key={props.id} className={postCardWithBG}>
</Row>

带 div:

className="div" 只是为 div 提供宽度和高度。

<div className="div" style={{ backgroundImage: `url('./leigh.png')` }}></div>
</div>

更完整的代码示例:

import React from "react"
import PropTypes from "prop-types"
import '../scss/base.scss'
import { Link } from "gatsby"
import { CardTitle, CardText, Row, Col } from "reactstrap"
import Moment from "react-moment"
import UserBar from './UserBar/UserBar'
import ThumbUp from '@material-ui/icons/ThumbUp';
import AddCircle from '@material-ui/icons/AddCircle';
import Place from '@material-ui/icons/Place'

const PostCard = props => {

    let Background = './leigh.png'

    return (
        <>
          <div className="div" style={{ backgroundImage: `url('./leigh.png')` }}></div>
            <Row style={{ backgroundImage: `url('./leigh.png')` }} key={props.id} className={postCardWithBG}>
            </Row>
          </div>
        </>
     )
 }

【问题讨论】:

    标签: javascript css image sass styles


    【解决方案1】:

    尝试使用 require('./path-to-image') 作为图像 src。

    const background = require('./leigh.png');
    
    <div className="div" style={{ backgroundImage: `url(${background})` }}></div>
    

    【讨论】:

    • 我可以吻你。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-06-11
    • 2015-12-03
    • 1970-01-01
    • 2022-11-24
    • 2022-09-23
    • 2021-03-05
    • 2022-06-23
    • 2021-05-28
    相关资源
    最近更新 更多