<分享>React-native的utils工具库

408 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第8天,点击查看活动详情

1、px转dp (stylesKits.js)

// 设计稿的宽度 / 元素的宽度 = 手机屏幕 / 手机中元素的宽度
// 左边是px = 右边是dp
// => 手机中元素的宽度 = 手机屏幕 * 元素的宽度 / 设计稿的宽度

import { Dimensions } from 'react-native'
/**
 * 屏幕的宽度
 */
export const screenWidth=Dimensions.get("window").width
/**
 * 屏幕的高度
 */
export const screenHeight=Dimensions.get("window").height

/**
 * 将px转为dp
 * @param {Number} elePx 元素的宽度或者高度 单位 px
 */
export const pxToDp=(elePx)=> screenWidth * elePx / 375

使用

import React, { Component } from 'react'
import { View, Image, StatusBar } from 'react-native'
import { pxToDp } from "../../../utils/stylesKits"

class Index extends Component {
    render() {
        return (
            <View>
                {/* 0.0状态栏开始 */}
                <StatusBar backgroundColor="transparent" translucent={ true } />
                {/* 0.0状态栏结束 */}
                {/* 1.0 背景图片 开始 */}
                <Image style={{ width: "100%", height: pxToDp(200) }} source={ require('../../../res/profileBackground.jpg') }></Image>
                {/* 1.0 背景图片 结束 */}
            </View>
        )
    }
}

export default Index

2、正则校验器(校验手机号码和富文本)validator.js

export default {
    /**
     * 校验手机号码
     * @param {Number} phone 
     */
    validatePhone(phone) {
      const reg = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;
      return reg.test(phone)
    },
    /**
     * 匹配富文本
     * @param {String} text 富文本内容
     */
    renderRichText(text) {
      //  声明最终要拿到的数组
      const finalList = [];
      //  定义一下正则
      const rule = /(/{.+?})/g;
      // 匹配后的图片字符的数组
      // ["/{fadai}", "/{fanu}", "/{aoman}"]
      const emoArr = text.match(rule);
      if (emoArr === null) {
        finalList.push({ text: text });
      } else {
        // "广东人以后¥¥搞笑¥¥¥¥吃饭"
        // ["广东人以后","","搞笑","","","吃饭"]
        //  ["/{fadai}", "/{fanu}", "/{aoman}"]
        const textArr = text.replace(rule, "¥¥").split("¥¥");//["广东人以后","","搞笑","","","吃饭"]
        while (textArr.length) {
          finalList.push({ text: textArr.shift() });
          if (emoArr.length) {
            finalList.push({ image: emoArr.shift() });
          }
        }
      }
      return finalList;
    }
  }

4、请求封装(request.js) axios

import axios from 'axios'
import { BASE_URI } from './pathMap'
import Toast from './Toast'

const instance = axios.create({
    baseURL: BASE_URI
})

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    Toast.showLoading('正在请求中...')
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    Toast.hideLoading()
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

export default {
    get: instance.get,
    post: instance.post
}

5、小提示框封装(Toast.js)

import React from 'react'
import { ActivityIndicator } from 'react-native'
import { Toast, Theme } from 'teaset'

let customKey = null;

Toast.showLoading = (text) => {
  if (customKey) return;
  customKey = Toast.show({
    text,
    icon: <ActivityIndicator size='large' color={Theme.toastIconTintColor} />,
    position: 'center',
    duration: 100000,
  });
}

Toast.hideLoading = () => {
  if (!customKey) return;
  Toast.hide(customKey);
  customKey = null;
}

export default Toast

最后

公众号:小何成长,佛系更文,都是自己曾经踩过的坑或者是学到的东西

有兴趣的小伙伴欢迎关注我哦,我是:何小玍。大家一起进步鸭