[英]How I can define image in React component if path to image I get from JSON file
I try to make a slider, information about each slide and image path I get from JSON.我尝试制作一个 slider,关于我从 JSON 获得的每张幻灯片和图像路径的信息。 So, it doesn't work.
所以,它不起作用。 I get page and I can see that element img have src="../../assets/img/1.png", but image don't show.
我得到页面,我可以看到元素 img 有 src="../../assets/img/1.png",但图像不显示。 So how I can add pictures or other files without "require" or "import"?
那么如何在没有“要求”或“导入”的情况下添加图片或其他文件? Sorry for my English.
对不起我的英语不好。
this is api.json file这是 api.json 文件
"gazel": {
"gazel1": {
"car_title": "Газель 3 метра",
"car_chars": {
"width": "2",
"height": "2",
"vol": "16",
"power": "1,5"
},
"img_src": "../../../assets/img/1.png"
},
"gazel2": {
"car_title": "Газель 3 метра (тентовая)",
"car_chars": {
"width": "2",
"height": "2",
"vol": "16",
"power": "2"
},
"img_src": "../../../assets/img/1.png"
}
}
and this is component这是组件
import React, {Component} from 'react';
import api from "../../../api/_api.json"
class SliderItems extends Component {
render() {
let arr = []
for(let car in cars){
arr.push(
<div className="slider__item">
<div className="slider__descr">
<h4 className="car_name">{cars[car].car_title} </h4>
<ul className="car_descr">
<li className="descr_item">Ширина {cars[car].car_chars.width} м</li>
<li className="descr_item">Высота {cars[car].car_chars.height} м</li>
<li className="descr_item">Объем {cars[car].car_chars.vol} м³</li>
<li className="descr_item">Грузоподъемность {cars[car].car_chars.power} т</li>
</ul>
<button className="btn">Заказать</button>
</div>
<div className="slider__img">
<img src={cars[car].img_src} alt="car"/>
</div>
</div>
)
}
return (
arr
)
}
}
let cars = api.gazel;
class SliderLine extends Component {
render() {
return (
<div className={"slider__line"}>
<SliderItems cars={cars}/>
</div>
);
}
}
export default SliderLine;
You are not able to dynamically load images from static this way (if I understood it properly.) My workaround: load image from server API this way: On server read file and send it to client:您无法以这种方式从 static 动态加载图像(如果我理解正确的话。)我的解决方法:以这种方式从服务器 API 加载图像:在服务器读取文件并将其发送到客户端:
fs.readFile(slidePath, (err, buf) => {
if (err) {
console.log('ERROR READING FILE: ', err);
rej(`ERROR READING FILE ON SEND SLIDE ${err}`)
} else if (ws) {
ws.send( // I use websocket, you send it with some REST API
JSON.stringify({
route,
action,
img: buf.toString('base64'), // image data, most important!
data,
})
);
and process on client this way:并以这种方式在客户端处理:
<div className="slidesTable" key={i}>
<img width="150px" alt={s} src={`data:image/jpg;base64,${data_from_api}`} />
</div>
All is part of my code, so you will not need everything一切都是我的代码的一部分,所以你不需要一切
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.