记react比较好用的插件及使用方法,不常用的功能性代码(最新更新时间 2023-8-23)

在hooks里动态创建ref的方式

import React, {useRef, useState} from "react";
const  Index = () => {
 const dom = useRef({}) //默认值要设置成对象,不然动态将ref赋值给modo将会报错
 const arr = [{name:'1'},{name:'2'}]
 return <div>
    {arr.map((item,index)=>{
    return  <div key={index} ref={node => dom.current['domRef'+index] = node}>
       {item.name}
    </div>
    })}
 <div>
}
export default Index 

十二、神奇的react-jsx-parser,专门用来解析react的jsx字符串。

此插件一般用在请求数据渲染不同内容的情况,比如报告模板,它比dangerouslySetInnerHTML好的地方在于支持react组件的导入,动态数据的渲染,下图例子展示

import {Checkbox, Col,  Row,Image,Radio,QRCode} from "antd";
import dayjs from 'dayjs'
import JsxParser from 'react-jsx-parser'
import './reportTemplate.css'
import Barcode from "../../../components/Barcode";
import checkedImg from '../../../images/checked.png'
import nocheckedImg from '../../../images/nochecked.png'

const ReportTemplate = (props) => {
    //jsx内容例子
    //<Row>
	//	<Col>
	//	  {baseInfo.name}
	//	</Col>
	//	<Image src={checkedImg} />
	//</Row>
  let {formValue,baseInfo,jsx} = props
  return <JsxParser
    components={{ Row, Col,Checkbox,Image,Radio,Barcode,QRCode}}  ///用来传jsx使用到的组件
    bindings={{baseInfo,formValue,dayjs,getUrlId,checkedImg,nocheckedImg}} ///用来传jsx使用到的数据
    jsx={`${jsx}`}  //用来传jsx字符串
  />
}
export default ReportTemplate

需要注意的一点是,如果jsx的写法不规范,那么此插件渲染出的内容为空,要检测下
更多使用方式点击这里

十一、表单设置值,清除或添加报错提示

this.orderRef.setFields([
  {
     name: ['otherProduct', index, 'productname'],  //index是Form.List组件,两层
     value: productname,
     errors: '错误提示,也可传空值,清除错误提示'
  },{
    name: ['pay_time'],//正常一层设置
    value: productname,
    errors: '错误提示,也可传空值,清除错误提示'
  },
]);

十、GetUrlParam 获取url传值

//GetUrlParam   根据url获取参数,同时兼容了无url时获取当前页面传的值
function GetUrlParam(name, url) {
  // 获取url里的参数,name为想要获取参数的名称
  var search = window.location.search;
  if (url) {
    search = '?' + url.split('?')[1];
  }
  if (search.length <= 1) {
    return null;
  } else {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'); //构造一个含有目标参数的正则表达式对象
    var r = search.substr(1).match(reg); //匹配目标参数
    if (r != null) return decodeURI(r[2]);
    return null; //返回参数值
  }
}
export { GetUrlParam };

九、当前页面要加载一个js文件

import Script from 'react-load-script';

 <Script url="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js" />

八、base64转换

import {Base64} from 'js-base64'
//解码
Base64.decode(token[1])
//编码
Base64.encode(token[1])

七、调起浏览器打印功能打印页面指定内容

import ReactToPrint from 'react-to-print';
<ReactToPrint
     trigger={()=><Button>打印</Button>}
     content={()=>this.componentRef}
     //portrait:竖屏打印   landscape:横屏打印   margin:四边的空白大小
     //不同的浏览器,打印展示的效果不一致,需要自行调整,其中谷歌的展示效果是  最好的
     pageStyle={`@page {size:A4 landscape;margin:10mm}`}  
 />
 <div ref={el => (this.componentRef = el)}>
     ///打印的内容,巴拉巴拉小魔仙
 </div>

六、中文转拼音

import pinyin from 'js-pinyin'

pinyin.getFullChars(item?.name)

五、条形码插件

import JsBarcode from 'jsbarcode';

///    
componentDidMount() {
 JsBarcode(this['barcode'], value, {
        displayValue: false,
        width: 1.5,
        height: 50,
        margin: 0,
    });
}

<svg
  ref={(ref) => {
    this['barcode'] = ref;
  }}
/>

四、图片查看插件

//https://www.npmjs.com/package/react-viewer#viewerimagesize

import Viewer from 'react-viewer';  ///图片查看插件

showInspectionSheet =(files,index) =>{
    let imageList = [];
    files.map((item)=>{
        imageList.push({src:item.file})
    });
    // console.log(imageList)
    this.setState({
        visible:true,
        imageList:imageList,
        activeIndex:index,
    })
};                  

<Viewer
    visible={visible}
    onClose={()=>{
        this.setState({
            visible:false
        })
    }}
    activeIndex={activeIndex}
    images={imageList}
/>     

三、项目添加版本对比文件,强制刷新,保证项目不停的更新,浏览器也能访问最新的代码

//version.js    版本对比文件方法
window.app_version = 'v20220418_1'; ///当前版本号,更新前手动修改
console.log('版本号加载了,'+app_version);

function addQueryStringArg () {
   window.location.reload();
}

window.old_version = window.localStorage.getItem('app_version');

if (window.app_version !== window.old_version) {
   window.localStorage.setItem('app_version', app_version);
   addQueryStringArg();
}

//第一次打开时触发,这个是放在项目的入口文件的<script></script>里
window.onload = function(){
  let sc = document.createElement('script');
  //加time是为了能每次加载最新的version.js文件,才能实现对比
  sc.src = '%PUBLIC_URL%/version.js?time=' + new Date().valueOf();
  document.body.appendChild(sc);
}

//考虑到用户并没有关闭页面,上面的方法触发不了,加了第二层保障,切换菜单时记载此文件

//如果是用的antdpro框架,在api.js文件的onPageChange方法添加下面的方法
let scripts = document.getElementsByTagName("script");
for (let i=0;i<scripts.length;i++) {//移出已加的version.js文件
    if (scripts[i] && scripts[i].src &&scripts[i].src.match('/version.js')){
        scripts[i].parentNode.removeChild(scripts[i]);
    }
}
let sc = document.createElement('script');
sc.src = '/version.js?time=' + new Date().valueOf();
document.body.appendChild(sc);

//如果是自己写的菜单,自己放在合适的地方吧

//以上基本上能保障用户在使用最新的项目

二、post默认传值类型 Content-Type: application/x-www-form-urlencoded;

let data = new URLSearchParams();
data.append('number',Number(values.number));
//将data当作对象直接传给接口

一、html存储为pdf文件

// 参考地址:https://blog.csdn.net/weixin_48003149/article/details/121333196
//先安装这两个插件
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas';
const handleExportPdf = async (refs) => {
	///refs是个对象,里面是需要保存为pdf的ref,ref只能是原始元素,比如说div,不能是组件
	//举个栗子   <div ref={node=>this.componentRef2=node} className='printtable1'></div>   
	//<Button onClick={()=>handleExportPdf([this.componentRef2])}>保存pdf</Button>
	//传值  refs = [this.componentRef2,...];可以传多个,最终会保存为多页的pdf

    // 根据dpi放大,防止图片模糊    refs类型是数组
    const scale = window.devicePixelRatio > 1 ? window.devicePixelRatio : 2;
    // 下载尺寸 a4 纸 比例
    const pdf = new jsPDF('l', 'pt', 'a4');//第一个参数: l:横向  p:纵向    第二个参数:测量单位("pt","mm", "cm", "m", "in" or "px")  第三个参数:默认为“a4”
    for(let i in refs){
        let toPdfRef = refs[i];
        let width = toPdfRef.offsetWidth;
        let height = toPdfRef.offsetHeight;
        console.log(width);
        console.log(height);
        const canvas = document.createElement('canvas');
        canvas.width = width * scale;
        canvas.height = height * scale;
        const pdfCanvas = await html2canvas(toPdfRef, {
            useCORS: true,
            canvas,
            scale,
            height,
            width,
            x: 0,
            y: 0,
        });
        const imgDataUrl = pdfCanvas.toDataURL();
        if(height > 14400){ // 超出jspdf高度限制时
            const ratio = 14400 / height;
            height = 14400;
            width = width * ratio;
        }

        // 缩放为 a4 大小  pdfpdf.internal.pageSize 获取当前pdf设定的宽高
        height = height * pdf.internal.pageSize.getWidth() / width;
        width = pdf.internal.pageSize.getWidth();

        // pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置
        pdf.addImage(imgDataUrl, 'png', 0, 0,width,height)

        // 若当前是最后一张截图,则不再另起一页,直接退出循环
        if(+i >= refs.length - 1){
            break;
        }

        // 另起一页
        pdf.addPage();
    }

    // 导出下载
    await pdf.save("pdf名", { returnPromise: true });
}
export {handleExportPdf}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值