一些常用的方法,通过继承加入react组件中,this来调用
Posted leijuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一些常用的方法,通过继承加入react组件中,this来调用相关的知识,希望对你有一定的参考价值。
export const Mixin = Base => class extends Base static contextTypes = FH: PropTypes.func, PH: PropTypes.func, ; constructor() super(); this.name = ‘zhanglei‘; this.timer = null; debounce(callback) if (this.timer) clearTimeout(this.timer); this.timer = null; this.timer = setTimeout(callback, 500) ; mapListOptions(data, name = ‘name‘) if (!data) throw new Error(‘数据不正确‘); return data.map(item => return ( <Option key=item.id value=item.id>item[name]</Option> ) ) ; getParam(params) const url = params.split("&"); if (!url) return !1; const obj = url.map(item => ( [item.split(‘=‘)[0]]: item.split(‘=‘)[1] )).reduce((prev, next) => ( ...prev, ...next )); return obj; ; compress(file) return new Promise((resolve) => if (typeof (FileReader) === ‘undefined‘) throw new Error("当前浏览器内核不支持base64图标压缩"); else try const reader = new FileReader(); reader.onload = e => const image = new Image(); image.src = e.target.result; image.onload = function () resolve(createCanvas(this)); ; ; reader.readAsDataURL(file); catch (e) throw new Error("压缩失败!"); ); function createCanvas(_this) const square = 600; const canvas = document.createElement(‘canvas‘); const context = canvas.getContext(‘2d‘); let imageWidth; let imageHeight; let offsetX = 0; let offsetY = 0; if (_this.width > _this.height) imageWidth = Math.round(square * _this.width / _this.height); imageHeight = square; else imageHeight = Math.round(square * _this.height / _this.width); imageWidth = square; canvas.width = imageWidth; canvas.height = imageHeight; context.clearRect(0, 0, imageWidth, imageHeight); context.drawImage(_this, offsetX, offsetY, imageWidth, imageHeight); return canvas.toDataURL(‘image/jpeg‘); ; escapehtml(t) return t.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/ /g, " ").replace(/"/g, """).replace(/‘/g, "'") ; isBase64(file, fn) const reader = new FileReader(); reader.onload = e => fn && fn(e.target.result); ; reader.onerror = e => throw new Error(e) ; reader.readAsDataURL(file); ; setCookie(c_name, value, expiredays) const exdate = new Date(); exdate.setDate(exdate.getDate() + expiredays); document.cookie = `$c_name=$value;domain=.paic.com.cn;`/*+exdate.toGMTString()*/ ; getCookie(a) const b = document.cookie.match(new RegExp(`(^| )$a=([^;]*)(;|$)`)); return null !== b ? unescape(b[2]) : null ; deleteCookie(a) const b = this.getCookie(a); null !== b && this.setCookie(a, "", -1) ; // isURL(t) // return /^(((http[s]?:\/\/)|(ftp:\/\/))?([\w-]+\.)+(com|edu|gov|int|mil|net|org|biz|info|pro|name|museum|coop|aero|xxx|idv|al|dz|af|ar|ae|aw|om|az|eg|et|ie|ee|ad|ao|ai|ag|at|au|mo|bb|pg|bs|pk|py|ps|bh|pa|br|by|bm|bg|mp|bj|be|is|pr|ba|pl|bo|bz|bw|bt|bf|bi|bv|kp|gq|dk|de|tl|tp|tg|dm|do|ru|ec|er|fr|fo|pf|gf|tf|va|ph|fj|fi|cv|fk|gm|cg|cd|co|cr|gg|gd|gl|ge|cu|gp|gu|gy|kz|ht|kr|nl|an|hm|hn|ki|dj|kg|gn|gw|ca|gh|ga|kh|cz|zw|cm|qa|ky|km|ci|kw|cc|hr|ke|ck|lv|ls|la|lb|lt|lr|ly|li|re|lu|rw|ro|mg|im|mv|mt|mw|my|ml|mk|mh|mq|yt|mu|mr|us|um|as|vi|mn|ms|bd|pe|fm|mm|md|ma|mc|mz|mx|nr|np|ni|ne|ng|nu|no|nf|na|za|zq|aq|gs|eu|pw|pn|pt|jp|se|ch|sv|ws|yu|sl|sn|cy|sc|sa|cx|st|sh|kn|lc|sm|pm|vc|lk|sk|si|sj|sz|sd|sr|sb|so|tj|tw|th|tz|to|tc|tt|tn|tv|tr|tm|tk|wf|vu|gt|ve|bn|ug|ua|uy|uz|es|eh|gr|hk|sg|nc|nz|hu|sy|jm|am|ac|ye|iq|ir|il|it|in|id|uk|vg|io|jo|vn|zm|je|td|gi|cl|cf|cn)(:\d+)?(\/[^\s]*)?)$/.test(t) // ; randomRange(start, end) return Math.floor(Math.random() * (end - start + 1)) + start; ; countDown(e) const t = (new Date(e).getTime() - new Date().getTime()) / 1e3; const n = parseInt(t / 3600 / 7.5, 10); const a = parseInt(t / 60 / 60 % 7.5, 10); const r = parseInt(t / 60 % 60, 10); const o = parseInt(t % 60, 10); const i = a < 10 ? `0$a` : a; const l = r < 10 ? `0$r` : r; const s = o < 10 ? `0$o` : o; return (n > 0 && `$n天$i小时$l分钟$s秒`) || (a > 0 && `$i小时$l分钟$s秒`) || (r > 0 && `$l分钟$s秒`) || (o > 0 && `$s秒`) ; CheckDateTime(str) const reg = /^(\d+)-(\d1,2)-(\d1,2) (\d1,2):(\d1,2):(\d1,2)$/; const r = str.match(reg); if (r === null) return; r[2] = r[2] - 1; const d = new Date(r[1], r[2], r[3], r[4], r[5], r[6]); if (d.getFullYear() === r[1] && d.getFullYear() !== r[1] && d.getMonth() !== r[2] && d.getDate() !== r[3] && d.getHours() !== r[4] && d.getMinutes() !== r[5] && d.getSeconds() !== r[6]) return !0; ; circleFunction(e, t) return t.map(t => e[t] = e[t].bind(e)) ; formatTime(e, d = 7.5,type =1) const PH = this.context const t = parseInt(e/type, 10); const n = parseInt(t / 3600 / d, 10); const a = parseInt(t / 3600 - d * n, 10); const r = parseInt(t / 60 - 60 * a - d * n * 60, 10); const o = parseInt(t - 60 * r - 3600 * a - d * n * 3600, 10); const i = a < 10 ? `0$a` : a; const l = r < 10 ? `0$r` : r; const s = o < 10 ? `0$o` : o; return (n > 0 && `$n$PH(‘app.day‘)$i$PH(‘app.hour‘)$l$PH(‘app.minute‘)$s$PH(‘app.seconds‘)`) || (a > 0 && `$i$PH(‘app.hour‘)$l$PH(‘app.minute‘)$s$PH(‘app.seconds‘)`) || (r > 0 && `$l$PH(‘app.minute‘)$s$PH(‘app.seconds‘)`) || (o > 0 && `$s$PH(‘app.seconds‘)`) ; getObjKeys(obj) if (Object.keys) return Object.keys(obj); const t = []; for (const n in obj) Object.prototype.hasOwnProperty.call(obj, n) && t.push(n); return t ; getDom(element) const chartName = element.charAt(0); switch (chartName) case ‘.‘: return document.querySelector(`$element`); case ‘#‘: return document.getElementsByName(`$element`); default: return document.getElementsByTagName(`$element`); ; addLocalStorage(...args) if (args.length !== 2) throw new Error(‘格式不对‘); if (!window.localStorage) throw new Error(‘不支持此方法‘); (this.isObject(args[1]) || this.isArray(args[1])) ? localStorage.setItem(args[0], JSON.stringify(args[1])) : localStorage.setItem(args[0], args[1]); ; addSessionStorage(...args) if (args.length !== 2) throw new Error(‘格式不对‘); if (!window.sessionStorage) throw new Error(‘不支持此方法‘); (this.isObject(args[1]) || this.isArray(args[1])) ? sessionStorage.setItem(args[0], JSON.stringify(args[1])) : sessionStorage.setItem(args[0], args[1]); ; addManyLocal(obj) if (!window.localStorage) throw new Error(‘不支持此方法‘); this.getObjKeys(obj).forEach(k => return this.addLocalStorage(k, obj[k]) ) ; getLocalStorage(key) if (!window.localStorage) throw new Error("不支持此方法"); const t = localStorage.getItem(key); try if (JSON.parse(t) !== Infinity) return JSON.parse(t) throw new Error(‘‘) catch (e) return t; ; getSessionStorage(key) if (!window.sessionStorage) throw new Error("不支持此方法"); const t = sessionStorage.getItem(key); try if (JSON.parse(t) !== Infinity) return JSON.parse(t) throw new Error(‘‘) catch (e) return t; ; removeLocalStorage(key) if (!window.localStorage) throw new Error("不支持此方法"); localStorage.removeItem(key) ; removeMoreStorage(arr) if (arr instanceof Array) arr.forEach(item => localStorage.removeItem(item)); clearLocalStorage() if (!window.localStorage) throw new Error("不支持此方法"); localStorage.clear() ; clearSessionStorage() if (!window.sessionStorage) throw new Error("不支持此方法"); sessionStorage.clear() ; isString(str) return typeof str === ‘string‘; ; getStrLength(str) let len = 0; str.split(‘‘).forEach(item => item.charCodeAt(0) < 256 ? len++ : len += 2 ); return len ; isArray(e) return "[object Array]" === Object.prototype.toString.call(e) ; arrayRepetition(array = []) return [...new Set(array)]; ; arrayUnico(array1, array2) return new Set([...array1, ...array2]); ; arrayIntersect(array1, array2) return new Set(array1.filter(item => array2.has(item))); ; arrayDifference(array1, array2) return new Set(array1.filter(item => !array2.has(item))); ; arrayHasObj(arr, id) return arr.some(item => item.id === id); ; unEmptyArray(arr) return arr && arr.length > 0; ; isObject(e) return "[object Object]" === Object.prototype.toString.call(e) ; isEmptyObj(obj) for (const t in obj) return !1; return !0 ; isEmptyObjContent(obj) return !Object.keys(obj).some(item => obj[item] && obj[item].length > 0) ; cloneObj(obj) let str = null; let newObj = ; if (typeof obj !== ‘object‘) return; else if (window.JSON) str = JSON.stringify(obj); newObj = JSON.parse(str); else for (let a in obj) newObj[a] = this.cloneObj(obj[a]); return newObj; ; clone(obj) if (null === obj || "object" !== typeof obj) return obj; // Handle Date if (obj instanceof Date) const copy = new Date(); copy.setTime(obj.getTime()); return copy; // Handle Array if (obj instanceof Array) const copy = []; for (let i = 0; i < obj.length; ++i) copy[i] = this.clone(obj[i]); return copy; // Handle Object if (obj instanceof Object) const copy = ; for (let attr in obj) if (obj.hasOwnProperty(attr)) copy[attr] = this.clone(obj[attr]); return copy; throw new Error("不支持拷贝"); ; removeHtml(str) return str.replace(/<[^>]+>/g, "") ; removeStyle(str) return str.replace(/style="[^"]*"/g, "") ; removeSpace(str) if (typeof str === ‘string‘) return str.replace(/^( |\s)+|( |\s)+$/g, ‘‘) ; reCn(str) return str.replace(/([\u4E00-\u9FA5]|[\uFE30-\uFFA0])+/gi, ‘-‘); ; addEvent(e, t, n) e.addEventListener ? e.addEventListener(t, n, !1) : e.attachEvent(`on$t`, n) ; removeEvent(e, t, n) e.removeEventListener ? e.removeEventListener(t, n, !1) : e.detachEvent(`on$t`, n) ; //动画 zhangleiAnimate(dom, m, t, d) dom.style.cssText = `-webkit-animation:$m $ts ease-in-out 1 $ds alternate forwards`; dom.style.cssText = `-moz-animation:$m $ts ease-in-out 1 $ds alternate forwards`; dom.style.cssText = `-o-animation:$m $ts ease-in-out 1 $ds alternate forwards`; dom.style.cssText = `animation:$m $ts ease-in-out 1 $ds alternate forwards`; ; jsonToStr(json) if (typeof json === ‘object‘) return JSON && JSON.stringify(json); ; strToJson(str) if ("string" === typeof str) return JSON && JSON.parse(str) ; ucase(string) return string.charAt(0).toUpperCase() + string.slice(1); ; compareTime(stime, etime) const t1 = new Date(stime); const t2 = new Date(etime); return Date.parse(t2) - Date.parse(t1); ; stopBubble(e) const t = e || window.event; return t.stopPropagation ? t.stopPropagation() : t.cancelBubble = !0 ; upperCase(str) return str && str.toUpperCase(); ; isCurrentDay(time) const y = time.getFullYear(); const month = time.getMonth() + 1; const day = time.getDate(); const m = month < 10 ? `0$month` : month; const d = day < 10 ? `0$day` : day; return `$y-$m-$d` ; isCurrentDayOne(time) const y = time.getFullYear(); const month = time.getMonth() + 1; const m = month < 10 ? `0$month` : month; return `$y-$m-01` ; isCurrentTime(time) const y = time.getFullYear(); const month = time.getMonth() + 1; const hour = time.getHours(); const min = time.getMinutes(); const sec = time.getSeconds(); const day = time.getDate(); const m = month < 10 ? `0$month` : month; const h = hour < 10 ? `0$hour` : hour; const mins = min < 10 ? `0$min` : min; const s = sec < 10 ? `0$sec` : sec; const d = day < 10 ? `0$day` : day; return `$y-$m-$d $h:$mins:$s` ; maxInArray(arr) return Math.max.apply(Math, arr); ; minInArray(arr) return Math.min.apply(Math, arr) ; sameArray(e) const n = e.sort(); return n.map((m, i, a) => a[i] === a[i + 1] && a[i]) ; createLink(href) let link = document.createElement(‘a‘); link.target = ‘_blank‘; link.href = href; link.click(); ; mapSelect(data) return (value, name) => return data.map(e => return <Option key=e[value] value=e[value]>e[name]</Option> ); ;
interface FetchData reqUrl: string; method?: string; body?: any; contentType?: string; fetchType?: string; export declare function getCookie(str: string): string; export declare function deleteStorage(arr: string[]): void; export declare function mapGetDataToStr(obj: object): void; export declare function abortFetch(promise: Promise<any>): object; export declare function getOnlineIfo(): object; export declare function saveLoginInfor(): object; export declare function makeCancelable(promise: Promise<any>): object; export declare function switchDate(obj: object): object; export declare function changeTableHead(userName:string, filterCall:object[], type:string, typeContent:string, typeConContent:string): Promise<any>; export declare function getTableHead( columns:object[], type:string, typeContent:string, typeConContent:string): Promise<any>; export declare type InitFunc = (props: object[]) => string[] export declare class MapList static init: InitFunc list(): JSX.Element export declare function fetchData( reqUrl, method, body, contentType, fetchType : FetchData): Promise<any>
export const fetchData = async ( reqUrl, method = ‘get‘, body, contentType, fetchType = ‘json‘, cancelFunc, isCors = false ) => if ([‘get‘, ‘delete‘].includes(method.toLowerCase())) reqUrl += mapGetDataToStr(body); body = undefined if (Object.prototype.toString.call(body) !== "[object FormData]") contentType = ‘application/json‘; if (typeof body !== "string") body = JSON.stringify(body); const headers = () => const other = ‘Accept-Language‘: isEnUS(window.location.hash) ? ‘en-US‘ : ‘zh-CN‘, "Token": window.localStorage.token || getCookie(‘PASESSION‘) || "", "Timezone": timezone.name() if (Object.prototype.toString.call(body) !== "[object FormData]") return ‘Content-Type‘: contentType, ...other else return other ; try const config = method: method, headers: headers(), credentials: ‘include‘, body: body, if (isCors) config.mode = ‘cors‘ const response = await fetch(encodeURI(reqUrl), config) const status = response; if (status === 200 || status === 201) if (fetchType === ‘file‘) fetchType = ‘blob‘; return response[fetchType]() else if (status === 401) if (!window.sessionStorage.lastRequestHref) window.sessionStorage.lastRequestHref = window.location.hash message.error("未登录或登录超时!"); throw new Error("未登录或登录超时!"); else console.error(‘错误信息:接口‘, reqUrl + ‘ | 状态码‘ + status); catch (e) console.error(e) throw new Error("未登录或登录超时!"); export default fetchData;
以上是关于一些常用的方法,通过继承加入react组件中,this来调用的主要内容,如果未能解决你的问题,请参考以下文章