React tsx generates a random verification code for your reference. The specific content is as follows I recently developed React using tsx. I didn’t find any good plugin for randomly generating verification codes, so I made one myself. Without further ado, here’s the code. The tsx file is as follows:React code snippet. import * as React from "react"; const size = 4; const verifycode = { width: "32%", height: "32px", marginLeft: "5%", display:"inline-block", position:"absolute" as "absolute", top:"0", right:"0", } export default class InputVerify extends React.Component<any, any> { constructor(props) { super(props); this.state = { options: id: "verifycode", //Container Id canvasId: "verifyCanvas", //canvas ID width: "150", //Default canvas width height: "47", //Default canvas height type: "blend", //Default type of graphic verification code blend: mixed type of numbers and letters, number: pure numbers, letter: pure letters code: "", numArr: "0,1,2,3,4,5,6,7,8,9".split(","), letterArr: this.getAllLetter(), } } } componentDidMount() { const self = this; setTimeout(() => { self._init(); self.refresh(); }, 100) this.props.onRef(this); // Call the function passed in by the parent component and assign itself to the parent component} _init() { let con = document.getElementById(this.state.options.id); let canvas = document.createElement("canvas"); this.state.options.width = con.offsetWidth > 0 ? con.offsetWidth : "150"; this.state.options.height = con.offsetHeight > 0 ? con.offsetHeight : "47"; canvas.id = this.state.options.canvasId; canvas.width = this.state.options.width; canvas.height = this.state.options.height; canvas.style.cursor = "pointer"; canvas.innerHTML = "Your browser version does not support canvas"; con.appendChild(canvas); let parent = this; canvas.onclick = function () { parent.refresh(); } } refresh() { this.state.options.code = ""; let canvas : any = document.getElementById(this.state.options.canvasId); let ctx = null; if (canvas.getContext) { ctx = canvas.getContext('2d'); } else { return; } ctx.clearRect(0, 0, this.state.options.width, this.state.options.height); ctx.textBaseline = "middle"; ctx.fillStyle = this.randomColor(180, 240); ctx.fillStyle = "rgba(0,0,0,0)"; //Background color ctx.fillRect(0, 0, this.state.options.width, this.state.options.height); if (this.state.options.type == "blend") { //Judge the verification code type var txtArr = this.state.options.numArr.concat(this.state.options.letterArr); } else if (this.state.options.type == "number") { var txtArr = this.state.options.numArr; } else { var txtArr = this.state.options.letterArr; } for (var i = 1; i <= size; i++) { var txt = txtArr[this.randomNum(0, txtArr.length)]; this.state.options.code += txt; ctx.font = this.randomNum(this.state.options.height / 2, this.state.options.height) + 'px SimHei'; //Randomly generate font size ctx.fillStyle = this.randomColor(50, 160); //Randomly generate font color// ctx.fillStyle = "rgb(46, 137, 255)";//Fixed font color ctx.shadowOffsetX = this.randomNum(-3, 3); ctx.shadowOffsetY = this.randomNum(-3, 3); ctx.shadowBlur = this.randomNum(-3, 3); ctx.shadowColor = "rgba(0, 0, 0, 0.3)"; var x = this.state.options.width / (size + 1) * i; var y = this.state.options.height / 2; var deg = this.randomNum(-30, 30); /**Set the rotation angle and coordinate origin**/ ctx.translate(x, y); ctx.rotate(deg * Math.PI / 180); ctx.fillText(txt, 0, 0); /**Restore the rotation angle and coordinate origin**/ ctx.rotate(-deg * Math.PI / 180); ctx.translate(-x, -y); } /**Draw interference line**/ for (var i = 0; i < 4; i++) { ctx.strokeStyle = this.randomColor(40, 180); ctx.beginPath(); ctx.moveTo(this.randomNum(0, this.state.options.width), this.randomNum(0, this.state.options.height)); ctx.lineTo(this.randomNum(0, this.state.options.width), this.randomNum(0, this.state.options.height)); ctx.stroke(); } } validate(code) { var code = code.toLowerCase(); var v_code = this.state.options.code.toLowerCase(); if (code == v_code) { return true; } else { this.refresh(); return false; } } /**Generate letter array**/ getAllLetter() { var letterStr = "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,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"; return letterStr.split(","); } /**Generate a random number**/ randomNum(min, max) { return Math.floor(Math.random() * (max - min) + min); } /**Generate a random color**/ randomColor(min, max) { var r = this.randomNum(min, max); var g = this.randomNum(min, max); var b = this.randomNum(min, max); return "rgb(" + r + "," + g + "," + b + ")"; } render() { return ( <div id="verifycode" style={verifycode}></div> ) } } Here, the style of verifycode is modified by yourself, generally a code snippet. import InputVerify from "../InputVerify" This way, the verification code can be automatically generated. How to verify it? I will simply post it here. The Form here uses antd, which you can understand at a glance. Code snippet. export default ($Child: any = {}) => { //Form submission method const onFinish = (values: any) => { if (values.vcode) { console.log($Child.validate(values.vcode))//Call child component method validation} }; const onFinishFailed = (errorInfo: any) => { console.log('Failed:', errorInfo); }; return ( <Form {...layout} name="basic" onFinish={onFinish} onFinishFailed={onFinishFailed} > <Form.Item name="vcode" rules={[{ required: true, message: 'Please enter the verification code' }]}> <Input size="large" className="security-code" placeholder="Please enter the verification code" /> </Form.Item> {/* Here, the parent component calls the child component method through onRef*/} <InputVerify onRef={(ref) => { $Child = ref }}></InputVerify> </Form> ) } The above writing method is indeed the old way of writing React. React 16.8 and later all use hooks, so I will also change it. The code is as follows: Code snippet. import * as React from "react"; const size = 4; const verifycode = { width: "32%", height: "32px", marginLeft: "5%", display:"inline-block", position:"absolute" as "absolute", top:"0", right:"0", } export default ({cRef}) => { const [code, setCode] = React.useState(Boolean); const [options, setOptions] = React.useState({ id: "verifycode", //Container Id canvasId: "verifyCanvas", //canvas ID width: 150, //Default canvas width height: 47, //Default canvas height type: "blend", //Default type of graphic verification code blend: mixed type of numbers and letters, number: pure numbers, letter: pure letters code: "", numArr: "0,1,2,3,4,5,6,7,8,9".split(","), letterArr: getAllLetter(),}); React.useImperativeHandle(cRef,()=>({ validate : (vcode) => { var vcode = vcode.toLowerCase(); var v_code = options.code.toLowerCase(); if (vcode == v_code) { setCode(true); } else { refresh(); setCode(false); } return code; } })); React.useEffect(()=>{ _init(); refresh(); }) function _init() { let con = document.getElementById(options.id); let canvas : any = document.createElement("canvas"); options.width = con.offsetWidth > 0 ? con.offsetWidth : 150; options.height = con.offsetHeight > 0 ? con.offsetHeight : 47; canvas.id = options.canvasId; canvas.width = options.width; canvas.height = options.height; canvas.style.cursor = "pointer"; canvas.innerHTML = "Your browser version does not support canvas"; con.appendChild(canvas); canvas.onclick = function () { refresh(); } } function refresh() { options.code = ""; let canvas : any = document.getElementById(options.canvasId); let ctx = null; if (canvas.getContext) { ctx = canvas.getContext('2d'); } else { return; } ctx.clearRect(0, 0, options.width, options.height); ctx.textBaseline = "middle"; ctx.fillStyle = randomColor(180, 240); ctx.fillStyle = "rgba(0,0,0,0)"; //Background color ctx.fillRect(0, 0, options.width, options.height); if (options.type == "blend") { //Judge the verification code type var txtArr = options.numArr.concat(options.letterArr); } else if (options.type == "number") { var txtArr = options.numArr; } else { var txtArr = options.letterArr; } for (var i = 1; i <= size; i++) { var txt = txtArr[randomNum(0, txtArr.length)]; options.code += txt; ctx.font = randomNum(options.height / 2, options.height) + 'px SimHei'; //Randomly generate font size ctx.fillStyle = randomColor(50, 160); //Randomly generate font color// ctx.fillStyle = "rgb(46, 137, 255)";//Fixed font color ctx.shadowOffsetX = randomNum(-3, 3); ctx.shadowOffsetY = randomNum(-3, 3); ctx.shadowBlur = randomNum(-3, 3); ctx.shadowColor = "rgba(0, 0, 0, 0.3)"; var x = options.width / (size + 1) * i; var y = options.height / 2; var deg = randomNum(-30, 30); /**Set the rotation angle and coordinate origin**/ ctx.translate(x, y); ctx.rotate(deg * Math.PI / 180); ctx.fillText(txt, 0, 0); /**Restore the rotation angle and coordinate origin**/ ctx.rotate(-deg * Math.PI / 180); ctx.translate(-x, -y); } /**Draw interference line**/ for (var i = 0; i < 4; i++) { ctx.strokeStyle = randomColor(40, 180); ctx.beginPath(); ctx.moveTo(randomNum(0, options.width), randomNum(0, options.height)); ctx.lineTo(randomNum(0, options.width), randomNum(0, options.height)); ctx.stroke(); } } /**Generate letter array**/ function getAllLetter() { var letterStr = "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,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"; return letterStr.split(","); } /**Generate a random number**/ function randomNum(min: any, max: any) { return Math.floor(Math.random() * (max - min) + min); } /**Generate a random color**/ function randomColor(min, max) { var r = randomNum(min, max); var g = randomNum(min, max); var b = randomNum(min, max); return "rgb(" + r + "," + g + "," + b + ")"; } return ( <div id="verifycode" style={verifycode}></div> ) } The call is also simple. The parent component declares a React.useRef and passes it to the child component. const childRef = React.useRef<any>(); //Here code is obtained through the onFinish event of antD's Form form //Call the child component method childRef.current.validate(code) <InputVerify cRef={childRef}></InputVerify> Well, the effect is as follows: The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM. You may also be interested in:
|
<<: How to set up virtual directories and configure virtual paths in Tomcat 7.0
>>: Mybatis fuzzy query implementation method
Configure Git environment in Docker At work, I en...
Mysql5.7.19 version is a new version launched thi...
HTML is a hybrid language used for publishing on ...
Table of contents Overview 1. Define store.js 2. ...
Because the server's database hard disk space...
Search Page: search.wxml page: <view class=&qu...
The simple installation configuration of mysql5.7...
The ogg process of a database produced some time ...
Rancher deployment can have three architectures: ...
The most understandable explanation of the accura...
Table of contents When declaring multiple variabl...
Any number of statements can be encapsulated thro...
1. Qualitative changes brought by CSS variables T...
Whitespace rules in HTML In HTML, multiple spaces...
Anchor tag usage: Linking to a specific location i...