DEV Community

打coding的奥特曼
打coding的奥特曼

Posted on

react 5分钟写一个乐透开奖

先放个效果图
Image description


import { useState } from 'react';
const Lottery = () => {
  const [pool,setPool]=useState([]) // 设置奖池初始值
  // 生成一个随机数字
  const randomNumber = (min, max) =>{
    const range = max - min + 1;
    const rand = Math.random() ;
    const num = Math.floor(rand * range + min);
    return num;
  }
  // 奖池生成器 
  const generator = (n,min,max)=>{
    const arr = [];
    while(arr.length<n){
      const num = randomNumber(min,max)
      if (arr.indexOf(num)===-1){
        arr.push(num)
      }
    }
    return arr;
  }

  return (
    <div>
      <button onClick={()=>setPool(generator(6,1,45))}>一键开奖</button>
      <button onClick={()=>setPool([])}>清空奖池</button>

      <div className="lottery">
        <ul>
          {pool.map((num,i)=>(<li key={i}><div>{num}</div></li>))}
        </ul>
      </div>
    </div>
  );
};

export default Lottery;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)