繁体   English   中英

动态添加背景图像在 React 中不起作用

[英]adding background-image dynamically not working in React

我正在尝试在 clientsSection 组件中显示图像。 我选择使用 div 元素并动态更改它们的背景图像,但图像没有显示出来。 如果我应用其他样式,它们会起作用,但不是背景图像。

我的组件:

import React from 'react';
import { clientsData } from './data';
import './clients.styles.css';

const ClientsSection = () => (
    <div className="clients-section-container">
        <h2>we've helped over 600 clients achieve</h2>
        <div className="clients-images">
            {
                clientsData.images.map(image => {
                    return <div  style={{ ...image }}></div>
                })
            }
        </div>

    </div>

)

export default ClientsSection;

数据文件:

export const clientsData = {
   images: [
       {
           'position': 'absolute',
           'width': '13%',
           'height': '30%',
           'left': '40%',
           'top': '20%',
           'backgroundImage': 'url(../../images/Vector-3.svg)',
           'backgroundSize': 'contain',
           'backgroundRepeat': 'no-repeat',

       },
       {
           'position': 'absolute',
           'width': '13%',
           'height': '30%',
           'left': '67%',
           'top': '22%',
           'backgroundImage': 'url("../../images/Vector-2.svg")',
           'backgroundSize': 'contain',
           'backgroundRepeat': 'no-repeat'
       }
   ]
}

顺便说一句,我将我的图像保存在公共文件夹中并且它正在工作,但我读到这是一种不好的做法(可能会导致构建问题)所以我在 /src/images 中更改了它们

我的组件在 /src/sections/clients-section 下

你试过这个吗?

backgroundImage: `url("path to image")`

尝试导入您要使用的图像,如下所示:

import first_image from './Assets/icons/airPlaneBlack.png';
import second_image from './Assets/icons/metro-printer.png';

然后在您的 DataFile 中使用它们,如下所示:

export const clientsData = {
  images: [
      {
          'position': 'absolute',
          'width': '13%',
          'height': '30%',
          'left': '40%',
          'top': '20%',
          'backgroundImage': `url(${first_image})`,
          'backgroundSize': 'contain',
          'backgroundRepeat': 'no-repeat',

      },
      {
          'position': 'absolute',
          'width': '13%',
          'height': '30%',
          'left': '67%',
          'top': '22%',
          'backgroundImage': `url(${second_image})`,
          'backgroundSize': 'contain',
          'backgroundRepeat': 'no-repeat'
      }
  ]
}

最后,您可以像这样在 UI 中显示它们:

<div >
    <h2>we've helped over 600 clients achieve</h2>
    <div >
        {
            clientsData.images.map(image => {
                return <div  style={{ ...image }}></div>
             })
        }
    </div>
</div>

您的输出将如下所示(我已删除样式,请稍后再添加):

在此处输入图片说明

暂无
暂无

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

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