react下实现验证码生成

来源:互联网 发布:经期 知乎 编辑:程序博客网 时间:2024/06/07 18:22

1.首先用一个函数生成一串随机的字符串(两种方法),我用str存生成的字符串:

方法1:这个方法不能生成大写的字符

changeCode=()=>{      this.setState({str:Math.random().toString(36).substr(2).substring(0,4)})     }
方法2:网上找的代码,str_0的值代表生成几位

 rnd_str=(str_0,str_1,str_2,str_3)=>{         var Seed_array=new Array();         var seedary;         var i;         Seed_array[0]=''         Seed_array[1]= 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z';         Seed_array[2]= 'a b c d e f g h i j k l m n o p q r s t u v w x y z';         Seed_array[3]= '0 1 2 3 4 5 6 7 8 9';         if (!str_1&&!str_2&&!str_3){str_1=true;str_2=true;str_3=true;}         if (str_1){Seed_array[0]+=Seed_array[1];}         if (str_2){Seed_array[0]+=' '+Seed_array[2];}         if (str_3){Seed_array[0]+=' '+Seed_array[3];}         Seed_array[0]= Seed_array[0].split(' ');         seedary=''         for (i=0;i<str_0;i++)         {         seedary+=Seed_array[0][Math.round(Math.random( )*(Seed_array[0].length-1))]         }         this.setState({str:seedary})        //下面为生成的字符串中的字符生成随机颜色        this.setState({            color0: this.getColor(),            color1: this.getColor(),            color2: this.getColor(),            color3: this.getColor(),            color4: this.getColor(),        })    } 
2.生成字符串之后就要为其随机生成颜色了,写一个随机生成颜色的方法:

//生成随机颜色    getColor=()=>{          var colorElements = '0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f';          var colorArray = colorElements.split(',');          var color ='#';          for(var i =0;i<6;i++){              color+=colorArray[Math.floor(Math.random()*16)];          }          return color;    }  
3.接下来写html:

<Input className="verify_input"/>

<div className="verify">     <span style={{color:this.state.color0}}>{this.state.str[0]}</span>     <span style={{color:this.state.color1}}>{this.state.str[1]}</span>     <span style={{color:this.state.color2}}>{this.state.str[2]}</span>     <span style={{color:this.state.color3}}>{this.state.str[3]}</span>     <span style={{color:this.state.color4}}>{this.state.str[4]}</span></div>
<a onClick={()=>{this.rnd_str(5,true,true,true)}}>看不清?换一张</a>
到此 ,就可以完成一个简陋的验证码生成的功能了,之所以把str字符串分开写是因为字符串中的每个字符颜色都不一样。。。

点击<a>标签切换验证码!







原创粉丝点击