我今天开始研究,我遇到了一个问题。在我的组件的渲染函数中,我已经指定了一个数组如下,其中image属性是图像的URL(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'}]
然后我使用map和以下子函数渲染它们:
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 + ')'}
}
创建所有框,并且每首歌曲的标题和作者都已成功从数组中拉出并正确列出。但是,背景图像仅适用于Web URL(数组中的第三个元素),而不适用于我的本地URL。如果我直接在css文件中使用它们,本地URL确实有效,但是,它们正确指向图像。
那我错过了什么?本地网址的格式是不正确的?
谢谢!
答案 0 :(得分:3)
如果您使用的是create-react-app,则需要使用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 :(得分:0)
您也可以使用“ require”:
style={{backgroundImage: `url(${require(`${songs[props.index].image}`)})`}}
在这种情况下,您可以使用图片地址