javascript - 如何通过 API 调用将图像添加到 React 而不是导入图像?
问题描述
我正在尝试使用具有图像 url 作为对象一部分的数据。通常,您将分配导入图像并将其分配给变量。但是,我无法做到这一点,因为我计划使用 API 调用来获取此图像 url。目前我正在使用模拟数据并且无法成功渲染图像。我想向<InfoWindow>
组件添加图像。
我试过了:
<img src={selectedSite.image} alt={`alien ${selectedSite.eventType}`} />
<img src={require(`${selectedSite.image}`} alt={`alien ${selectedSite.eventType}`} />
模拟数据
export const mockSightings = [
{
name: '',
lat: '47.7511',
lng: '-120.7401',
description: 'BIG BLUE BALL IN SKY OMG',
eventType: 'sighting',
image: 'https://cdn.mos.cms.futurecdn.net/QkuLCPzH7GUVS9MthdWM9M.jpg',
},
{
name: 'Billy Bob',
lat: '43.8041',
lng: '-120.5542',
description: 'BIG RED BALL IN SKY OMG',
eventType: 'sighting',
image: 'https://ewscripps.brightspotcdn.com/dims4/default/3402aa2/2147483647/strip/true/crop/1000x563+0+0/resize/1280x720!/quality/90/?url=http%3A%2F%2Fewscripps-brightspot.s3.amazonaws.com%2F5a%2F57%2F58a3662b422a8fb6464451f244eb%2Flarge-fireball-seen-across-fl-sky-mari-g.png',
},
{
name: 'Stephanie Jo',
lat: '44.0682',
lng: '-114.7420',
description: 'rotating lights',
eventType: 'sighting',
image: 'https://i.dailymail.co.uk/i/pix/2016/10/04/01/391305FA00000578-3820675-image-a-23_1475542666609.jpg',
}
]
零件
import React, { useState } from "react";
import {
GoogleMap,
useJsApiLoader,
Marker,
InfoWindow,
} from "@react-google-maps/api";
import { mockSightings } from "../../mockdata";
const containerStyle = {
width: "1500px",
height: "800px",
};
const center = {
lat: 39.8283,
lng: -98.5795,
};
const SightingsMap = () => {
const [selectedCenter, setSelectedCenter] = useState(null);
const [selectedSite, setSelectedSite] = useState(null);
const { isLoaded } = useJsApiLoader({
id: "google-map-script",
googleMapsApiKey: `${process.env.REACT_APP_API_KEY}`,
});
const generateMarkers = () => {
return mockSightings.map((sighting) => {
const position = {
lat: parseInt(sighting.lat),
lng: parseInt(sighting.lng),
};
return (
<Marker
position={position}
onMouseDown={() => {
setSelectedSite(sighting);
}}
onMouseUp={() => {
setSelectedCenter(position);
}}
/>
);
});
};
return isLoaded ? (
<GoogleMap mapContainerStyle={containerStyle} center={center} zoom={5}>
{generateMarkers()}
{selectedCenter && (
<InfoWindow
onCloseClick={() => {
setSelectedCenter(null);
}}
position={selectedCenter}
>
<div>
<div>
<p>{selectedSite.name ? selectedSite.name : "anonymous"}</p>
<p>{selectedSite.description}</p>
<p>{selectedSite.eventType}</p>
</div>
<img src={selectedSite.image} alt={`alien ${selectedSite.eventType}`} />
</div>
</InfoWindow>
)}
</GoogleMap>
) : (
<></>
);
};
export default SightingsMap;
解决方案
尝试
<img src={`${selectedSite.image}`}/>