【问题标题】:Adding background to div using props使用道具为div添加背景
【发布时间】:2020-01-03 11:58:17
【问题描述】:

我正在创建一个滑块并使用 prop 向其中添加数据。每个幻灯片 div 都有一个标题和说明。我还想为每个 div 赋予不同的图像背景。是否可以使用道具向 div 添加背景图像?

这是我的方法,但它不起作用:

const slideData = [
    {
        id: 1,
        heading: "First Heading",
        description: "A short description of the service goes here",
        image: './images/candle.jpg'
    },
    {
        id: 2,
        heading: "Second Heading",
        description: "A short description of the service goes here",
        image: './images/candle.jpg'
    },
    {
        id: 3,
        heading: "Third Heading",
        description: "A short description of the service goes here",
        image: './images/candle.jpg'
    },
    {
        id: 4,
        heading: "Fourth Heading",
        description: "A short description of the service goes here",
        image: './images/candle.jpg'
    }
]

export default slideData

子组件

import React from 'react';

function Slide(props) {
    return (
        <div className="slide" style={{background: props.image}}>
            <h3> { props.heading} </h3>
            <p> { props.description} </p>
        </div>
    );
}

export default Slide;

【问题讨论】:

  • 您是否检查过背景图像的路径是否正常?

标签: javascript node.js reactjs ecmascript-6


【解决方案1】:

也许这段代码 sn-p 会帮助你

style={{ backgroundImage: `url(${props.image})`

【讨论】:

    【解决方案2】:

    是的,您实际上是在寻找backgroundImage 属性。要与props 一起使用,您需要使用string-interpolation

    查看工作沙箱:https://codesandbox.io/s/solitary-lake-fey03

    function Slide(props) {
      return (
        <div className="slide" style={{ backgroundImage: `url(${props.image})` }}>
          <h3> {props.heading} </h3>
          <p> {props.description} </p>
        </div>
      );
    }
    
    export default Slide;
    

    【讨论】:

    • @TalhaMunir 如果您需要参考,我已经添加了一些猫图片和实际的滑块功能 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2018-12-14
    • 2014-04-05
    • 1970-01-01
    • 2017-02-21
    相关资源
    最近更新 更多