一些常用的方法,通过继承加入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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /g, "&nbsp;").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+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,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(/^(&nbsp;|\s)+|(&nbsp;|\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} ${t}s ease-in-out 1 ${d}s alternate forwards`;
        dom.style.cssText = `-moz-animation:${m} ${t}s ease-in-out 1 ${d}s alternate forwards`;
        dom.style.cssText = `-o-animation:${m} ${t}s ease-in-out 1 ${d}s alternate forwards`;
        dom.style.cssText = `animation:${m} ${t}s ease-in-out 1 ${d}s 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;

原文地址:https://www.cnblogs.com/leijuan/p/11348005.html

时间: 2024-11-14 13:01:36

一些常用的方法,通过继承加入react组件中,this来调用的相关文章

一些常用的方法(1)--去除DataTable中的重复数据

private DataTable Display(DataTable dtSource)        {            DataTable dtTemp = dtSource.Copy();            foreach (DataRow dr in dtSource.Rows)            {                DataRow[] drRepeat = dtTemp.Select("AA='" + dr["AA"].ToS

规避 React 组件中的 bind(this)

React 组件中处理 onClick 类似事件绑定的时候,是需要显式给处理器绑定上下文(context)的,这一度使代码变得冗余和难看. 请看如下的示例: class App extends Component { constructor() { super(); this.state = { isChecked: false }; } render() { return ( <div className="App"> <label > check me: &

关于react组件中的constructor和super

正片 export default class Child extends React.Component { constructor(props) { super(props); // ... } // ... } 简单来说,react 中通过继承的方式定义 class 组件时,可以缺省 constructor 构造函数,由 ES6 的继承规则得知,不管子类写不写 constructor,在 new 实例的过程都会给补上 constructor. 但是如果需要定义实例的 state 状态时,则

Angular 中的 dom 操作(ViewChild)以及父子组件中通过 ViewChild 调用子组件的方法

<app-header #header></app-header> <div #myBox> 我是一个dom节点 </div> <button (click)="getChildRun()">获取子组件的方法</button> /* ViewChild获取dom节点 1.模板中给dom起一个名字 <div #myBox> 我是一个dom节点 </div> 2.在业务逻辑里面引入ViewChi

StringUtils中的常用的方法

org.apache.commons.lang.StringUtils中常用的方法,这里主要列举String中没有,且比较有用的方法: 1. 检查字符串是否为空: static boolean isBlank(CharSequence str)  判断字符串是否为空或null;  static boolean isNotBlank(CharSequence str) 判断字符串是否非空或非null; StringUtils.isBlank("a");  返回结果为: false; 2.

react组件的数据传递

在react中,为了解决html标签构建应用的不足,将公共的功能单独抽离成一个文件作为一个组件,在使用的地方按需引入,既然是组件彼此调用,就会涉及到父子组件的通信,下面主要来总结简单的组件通信. 1,项目准备 在开始组件通信前,先在components中新建两个文件,News.js和Header.js,并在News.js中引用Header.js,然后在App.js中引入News.js. App.js Header.js News.js 2,父组件给子组件传值 要在子组件中获取父组件传递的值,只需

vue组件之间的通信以及如何在父组件中调用子组件的方法和属性

在Vue中组件实例之间的作用域是孤立的,以为不能直接在子组件上引用父组件的数据,同时父组件也不能直接使用子组件的数据 一.父组件利用props往子组件传输数据 父组件: <div> <child v-bind:my-message="parentMsg"></child>//注意传递参数时要用-代替驼峰命名,HTML不区分大小写 </div> 子组件: Vue.component('child', { // camelCase in Ja

java中常用的包、类、以及包中常用的类、方法、属性-----io包

由于最近有需要,所以下面是我整理的在开发中常用的包.类.以及包中常用的类.方法.属性:有需要的看看 java中常用的包.类.以及包中常用的类.方法.属性 常用的包 java.io.*; java.util.*; java.lang.*; java.math.*; java.sql.*; java.text.*; java.awt.*; javax.swing.*;   包名 接口 类 方法 属性 java.io.*; java.io.Serializable实现序列化 java.io.Buffe

magic method细解python一直让我疑惑的几个常用魔法方法(上)

这里只分析几个可能会常用到的魔法方法,像__new__这种不常用的,用来做元类初始化的或者是__init__这种初始化使用的 每个人都会用的就不介绍了. 其实每个魔法方法都是在对内建方法的重写,和做像装饰器一样的行为.理解这个道理 再尝试去理解每个细节装饰器会比较方便. 关于__str__和__repr__: 直接上例子: class Test(object): def __init__(self, world): self.world = world def __str__(self): re