如何从对象数组中随机显示一个1图像
如何随机显示单个图像? 我创建了一个对象数组,现在添加了图像,我需要随机显示这些图像,但会一次显示这些图像,并且会在下一个重新加载中发生变化。
const index= () => {
let gifGallery=[
{
src:'./Images/1.gif',
value:1
},
{
src:'./Images/2.gif',
value:2
},
{
src:'./Images/3.gif',
value:3
},
{
src:'./Images/4.gif',
value:4
},
]
return (
<>
<h1>Gif Gallery</h1>
<div>
{
what should be the logic here?????
}
</div>
</>
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用此代码
use this code
使用
MATH.FLOOR()
,您可以在此链接,我希望这会有所帮助。谢谢use
Math.floor()
, you can see the docs on this link, I hope this would be helpful. thanks一种方法是在图像数组的0和最后一个索引之间生成一个随机数。理想情况下,您将其存储在
usestate
中,以便在需要时可以更改它(例如,您的按钮说“获取随机GIF”)。您将需要这样的函数来生成
RandomIdx
:创建此类函数的方法在此处。
然后,您将放入JSX和
&lt; img/&gt;
标签,其src
属性存储在对象的src属性中,atgifgallery [rancomidx]
。您在此反应游乐场
One way would be to generate a random number between 0 and the last index of your image array. Ideally you'd store it in a
useState
, so that you can change it when you want (say for instance you have a button that says "get random GIF").You would need a function like this one to generate the
randomIdx
:The way to create such functions is well explained in here.
You would then put in your JSX an
<img />
tag, whosesrc
attribute is stored in the src property of the object atgifGallery[randomIdx]
.you have a working exemple in this React Playground