如何将图像从JSON数据导入到create-react-app [英] How to import images from JSON data into create-react-app
本文介绍了如何将图像从JSON数据导入到create-react-app的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有JSON数据,该数据包括位于我的公用文件夹(/ public / images)中的图像的路径。像这样,
So I have JSON data that includes the path to the images thats located in my public folder (/public/images). Like so,
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"
},
根据其他一些类似情况,这就是我在组件中尝试过的内容;
And based on reading a few other similar situations, this is what I've tried in my component;
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'
But create-react-app throws the error "Error: Cannot find module '../public/images/test.jpg'
任何
推荐答案
我们不能动态使用require。您可以像这样更改数据。
we can not use require dynamically.you can change your data like this.
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")
}
]
这篇关于如何将图像从JSON数据导入到create-react-app的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文