2017-05-25 100 views
0

我今天开始研究反应,并且遇到了问题。在我的组件的渲染功能我已经规定如下数组中,当图像属性是图片网址(Nattklunn旨在拼写错误):反应背景图像样式不适用于本地图像

const songs = [{'title' : 'Nattklubb', 
        'author' : 'DigohD', 
        'image' : 'img/Nattklunn.png'}, 

        {'title' : 'LED Beluga', 
        'author' : 'DigohD', 
        'image' : 'img/LED Beluga.png'}, 

        {'title' : 'LED Elephantasia', 
        'author' : 'DigohD', 
        'image' : 'http://ovk.no/wp-content/uploads/2012/08/Husmus-Mus-Musculus.jpg'}] 

然后,我使它们都使用地图和下面的子功能:

function LBoxContent(props){ 
     return <div className="lBoxContent" style={lContentStyle(props)}> 
      {songs[props.index].title} 
      <br /> 
      {songs[props.index].author} 
     </div> 
    } 

    function lContentStyle(props){ 
     return {backgroundImage: 'url(' + songs[props.index].image + ')'} 
    } 

所有的盒子都被创建,并且每首歌曲的标题和作者被成功地从数组中拉出并正确列出。但是,背景图片仅适用于网址(数组中的第三个元素),而不适用于我的本地网址。如果我直接在css文件中使用它们,本地网址会有效,但是,它们正确地指向图像。

那么我错过了什么?本地网址的格式不正确吗?

谢谢!

+1

我认为,本地路径应该与开始任基于文件夹结构的'.'或'..',如果img文件夹存在于同一级别,请尝试使用''image':'./img/Nattklunn.png'',否则使用'..'。 –

+0

感谢您的答案Mayank。这确实是正确的格式,但是我也必须导入像Damien建议的图像。 –

回答

2

如果您使用的创建 - 反应 - 应用程序,你需要使用一个Javascript模块导入图像:

import nattklunn from './img/Nattklunn.png'; // import logo from '/img/Nattklunn.png'; if img is a folder at root. 

[...] 

const songs = [{'title' : 'Nattklubb', 
       'author' : 'DigohD', 
       'image' : nattklunn}, 

       {'title' : 'LED Beluga', 
       'author' : 'DigohD', 
       'image' : nattklunn}, 

       {'title' : 'LED Elephantasia', 
       'author' : 'DigohD', 
       'image' : nattklunn} 
       }] 

然后:

function LBoxContent(props){ 
    return <div className="lBoxContent" style={lContentStyle(props)}> 
     {songs[props.index].title} 
     <br /> 
     {songs[props.index].author} 
    </div> 
} 

function lContentStyle(props){ 
    return {backgroundImage: `url(${songs[props.index].image})`} 
} 
+1

谢谢达米安!奇迹般有效! –