所以我有JSON数据,该数据包括位于我的公用文件夹(/ public / images)中的图像的路径。像这样
const data = [
{
"key": 1,
"name": "Goal Squad",
"techs": ["React & Redux", "Express", "MySQL"],
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et",
"image": "../public/images/test.jpg"
},
{
"key": 2,
"name": "WesterosCraft",
"techs": ["React & Redux", "Express", "MySQL"],
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et",
"image": "../public/images/test.jpg"
},
根据阅读的其他一些类似情况,这就是我在组件中尝试过的内容;
class Card extends Component {
render() {
const { name, description, image } = this.props;
const items = Object.values(this.props.techs);
console.log(this.props)
return (
<CardWrapper>
<Row>
<Column colmd6 colsm12>
<Header card>{name}</Header>
<TechList>{items.map(tech =>
tech
).join(' / ')}</TechList>
<Text regular>{description}</Text>
<Button>Visit Website</Button>
</Column>
<Column colmd6 colsm12>
<img src={require(`${image}`)} alt={name}/>
</Column>
</Row>
</CardWrapper>
)
}
但是create-react-app会引发错误“错误:找不到模块'../ public / images / test.jpg'
有任何提示吗?
答案 0 :(得分:1)
我们不能动态使用require。您可以像这样更改数据。
const data = [
{
"key": 1,
"name": "Goal Squad",
"techs": ["React & Redux", "Express", "MySQL"],
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et",
"image": require("../public/images/test.jpg")
},
{
"key": 2,
"name": "WesterosCraft",
"techs": ["React & Redux", "Express", "MySQL"],
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et",
"image": require("../public/images/test.jpg")
}
]
答案 1 :(得分:1)
module.exports = [
{
"key": 1,
"name": "Goal Squad",
"techs": ["React & Redux", "Express", "MySQL"],
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et",
"image": "../public/images/test.jpg"
},
{
"key": 2,
"name": "WesterosCraft",
"techs": ["React & Redux", "Express", "MySQL"],
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et",
"image": "../public/images/test.jpg"
}
]
答案 2 :(得分:1)
试试这个,它对我有用,
首先将文件/格式名称更改为 .js
而不是 .json
并像这样编辑代码。
import React from 'react';
import TestIMG1 from "../public/images/test.jpg";
import TestIMG2 from "../public/images/test.jpg";
export const data = [
{
key: 1,
name: "Goal Squad",
techs: ["React & Redux", "Express", "MySQL"],
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et",
image: TestIMG1
},
{
key: 2,
name: "WesterosCraft",
techs: ["React & Redux", "Express", "MySQL"],
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et",
image: TestIMG2
},
然后像这样将它导入到一个组件中:
{data.map((item) => {
return(
<div>
<img src={item.image} width="" height="" alt=""/>
</div>
)
})}