(Material UI) Проблема подключения картинки
Имеется ссылка, которая возвращает случайное изображение (https://picsum.photos/600/300), а также код элемента сетки. Как мне сделать так, чтобы каждый элемент имел разные изображения? Не имею предположений или вариантов как это можно сделать. Можно ли как-то обратиться к этой ссылке несколько раз, а не только один?
Элемент:
import * as React from 'react';
import { styled } from '@material-ui/core/styles';
import { Grid, Paper, Typography, ButtonBase, Box } from '@material-ui/core';
const Img = styled('img')({
width: '320px',
borderTopLeftRadius: '4px',
borderTopRightRadius: '4px'
});
export default function GridItem() {
return (
<Grid item>
<Paper sx={{width: 320}}>
<ButtonBase>
<Img alt="image" src="https://picsum.photos/600/300"/> // Собственно вот это та и ссылка
</ButtonBase>
<Box sx={{p:1}}>
<Typography variant="subtitle1">Crowd Prediction</Typography>
<Typography variant="caption">Crowd Predictions in Ford to forecast weekly vehicles sale volumes across business units</Typography>
</Box>
</Paper>
</Grid>
</Paper>
);
}
Сетка:
import * as React from 'react';
import Grid from '@material-ui/core/Grid';
import Item from './Item';
export default function Body(){
return(
<Grid sx={{width: '98%', mt:8}} container>
<Grid sx={{m: 'auto'}} container spacing={3}>
<Item/>
<Item/>
<Item/>
</Grid>
</Grid>
);
}
Ответы (1 шт):
Автор решения: Konstantin Modin
→ Ссылка
Сработало следующим методом: в GridItem создаём useEffect и стейт-хук. Далее в useEffect делаем запрос на указанный URL https://picsum.photos/600/300. Из ответа сохраняем готовую ссылку картинки в стейт-хук, он расположена в response.request.responseURL. И далее идёт отрисовка. Получается так:
GridItem.js:
function GridItem() {
const [link, setLink] = React.useState("");
React.useEffect(() => {
const fetchLink = async () => {
const response = await axios("https://picsum.photos/600/300");
setLink(response.request.responseURL);
};
fetchLink();
}, []);
return (
<Grid item>
<Paper sx={{ width: 320 }}>
<ButtonBase>
<Img alt="image" src={link} />
</ButtonBase>
<Box sx={{ p: 1 }}>
<Typography variant="subtitle1">Crowd Prediction</Typography>
<Typography variant="caption">
Crowd Predictions in Ford to forecast weekly vehicles sale volumes
across business units
</Typography>
</Box>
</Paper>
</Grid>
);
}
