我正在映射一組專案。某些專案必須顯示視頻,而其他專案必須顯示影像。我為每個顯示幕制作了 2 個函式,我使用 useState 來切換它們。
export default function App() {
//SIMPLE USESTATE TO TOGGLE WINDOW
const [open, setOpen] = useState(false);
//THE ARRAY (1 contains an image and the other a video)
const itemsArray = [
{
name: "Item1",
imageUrl: "some image url"
},
{
name: "Item2",
videoUrl: "some video url"
}
];
//RENDER THIS IF ITEM IS IMAGE
const ifImage = (i) => {
return (
<div onClick={() => setOpen(!open)}>
<img src={i} alt="cat" />
</div>
);
};
//RENDER THIS IF ITEM IS VIDEO
const ifVideo = (v) => {
return (
<div className="window-on-top" onClick={() => setOpen(!open)}>
<iframe>Some Video</iframe>
</div>
);
};
return (
<div className="App">
<h3>One button shows a cat photo and the other a cat video</h3>
{itemsArray.map((item) => {
return (
<div key={item.name}>
<button className="niceBtn" onClick={() => setOpen(!open)}>
{item.name}
</button>
{/* NESTING CONDITIONALS OR SOMETHING TO MAKE THIS WORK */}
{open ? {
{item.imageUrl ? ifImage(item.imageUrl): null}
||
{item.videoUrl ? ifVideo(item.videoUrl): null}
} : null}
</div>
);
})}
</div>
);
}
我顯然錯了......需要一些幫助來理解如何解決這個問題......這是一個包含正確觀看代碼的沙箱。 沙盒
uj5u.com熱心網友回復:
我將條件放在子函式中,這樣應該更容易理解發生了什么。
const tryImage = item => (
!item.imageUrl ? null : (
<div onClick={() => setOpen(!open)}>
<img src={item.imageUrl} alt="cat" />
</div>
));
const tryVideo = item => (
!item.videoUrl ? null : (
<div onClick={() => setOpen(!open)}>
<img src={item.videoUrl} alt="cat" />
</div>
));
return (
<div className="App">
<h3>One button shows a cat photo and the other a cat video</h3>
{itemsArray.map((item) => {
return (
<div key={item.name}>
<button className="niceBtn" onClick={() => setOpen(!open)}>
{item.name}
</button>
{open && ([
tryImage(item),
tryVideo(item),
])}
</div>
);
})}
</div>
);
不確定,但您可能還希望open陣列中的每個專案都有一個單獨的狀態,而不是整個應用程式的單個狀態。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366752.html
上一篇:陣列值意外更改
