在 React 中将数据数组映射到图像时出现问题
2022-06-05
131
2个回答
确保在
return
函数之后或内部添加映射数组
theLinks
,
例如,
这将不起作用
:
export default function App() {
const theLinks = [
{ lable: "Daily Mix", src: "https://flif.info/example-images/fish.png" },
{ lable: "Legit", src: "https://flif.info/example-images/fish.png" },
{ lable: "SCL", src: "https://flif.info/example-images/fish.png" }
];
{theLinks.map((item, indx) => (
<img
style={{ width: "50%", border: "1px solid #ccc" }}
key={indx}
src={item.src}
alt={item.label}
/>
))}
}
解决方案 1
这将起作用(同时渲染映射数组和其他元素):
export default function App() {
const theLinks = [
{ lable: "Daily Mix", src: "https://flif.info/example-images/fish.png" },
{ lable: "Legit", src: "https://flif.info/example-images/fish.png" },
{ lable: "SCL", src: "https://flif.info/example-images/fish.png" }
];
return (
<>
<h1> thanks Phil for your suggestion! </h1>
{theLinks.map((item, indx) => (
<img
style={{ width: "50%", border: "1px solid #ccc" }}
key={indx}
src={item.src}
alt={item.label}
/>
))}
;
</>
);
}
解决方案 2
这将起作用(仅渲染映射数组)
export default function App() {
const theLinks = [
{ lable: "Daily Mix", src: "https://flif.info/example-images/fish.png" },
{ lable: "Legit", src: "https://flif.info/example-images/fish.png" },
{ lable: "SCL", src: "https://flif.info/example-images/fish.png" }
];
return theLinks.map((item, indx) => (
<img
style={{ width: "50%", border: "1px solid #ccc" }}
key={indx}
src={item.src}
alt={item.label}
/>
));
}
omar
2022-06-05
尝试一下
{theLinks.map((item, indx) => { return ( <img key={indx} src={item.src} alt={item.label} /> ); })
Vishwaraj Kamble
2022-06-05