0
点赞
收藏
分享

微信扫一扫

盘点亚马逊5大实用选品思路(图文讲解+选品案例)

Raow1 2024-07-24 阅读 18

文章目录


前言

今天要封装的Qrcode 组件,是通过传入的信息,绘制在二维码上,可用于很多场景,如区块链项目中的区块显示交易地址时就可以用到。

Qrcode组件

1. 功能分析

2. 代码+详细注释

// @/components/Qrcode/index.tsx
import { useEffect, useRef, FC } from "react";
import QRCode from "qrcode";
import { ReactComponent as QrCodeIcon } from "./assets/qrcode.svg";
import { QrcodeContainer } from "./styled";
import classNames from "classnames";

// 组件的属性类型
type Props = {
  text: string; // 要绘制的二维码内容
  className?: string; // 自定义的类名
};

const Qrcode: FC<Props> = ({ text, className }) => {
  const qrRef = useRef<HTMLCanvasElement | null>(null);
  useEffect(() => {
    // 获取canvas元素ref
    const cvs = qrRef.current;
    // 如果没有 canvas 元素的引用,则直接返回
    if (!cvs) return;
    // 调用 QRCode.toCanvas 方法,将text绘制到canvas上
    QRCode.toCanvas(
      cvs,
      text,
      {
        margin: 5, // 设置二维码周围的边距
        errorCorrectionLevel: "H", // 设置二维码的容错级别
        width: 144, // 设置二维码的宽度
      },
      (err) => {
        if (err) {
          console.error(err);
        }
      }
    );
  }, [qrRef, text]); // 监听qrRef和text,当发生变化时重新绘制二维码

  return (
    <QrcodeContainer className={classNames(className)}>
      <label>
        <QrCodeIcon />
      </label>
      <canvas ref={qrRef} className={classNames("qrcode")} />
    </QrcodeContainer>
  );
};

export default Qrcode;
------------------------------------------------------------------------------
// @/components/Qrcode/styled.tsx
import styled from "styled-components";
import variables from "@/styles/variables.module.scss";
export const QrcodeContainer = styled.div`
  width: 100%;
  position: relative;
  cursor: pointer;
  label {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
  .qrcode {
    top: calc(100% + 10px);
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  }
  &::after {
    top: calc(100% - 15px);
    content: "";
    width: 5px;
    height: 5px;
    border: 10px solid transparent;
    border-bottom: 10px solid #fff;
    filter: drop-shadow(0 -5px 5px rgb(0, 0, 0, 0.1));
  }
  .qrcode,
  &::after {
    display: none;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }
  &:hover,
  &:focus-within {
    .qrcode,
    &::after {
      display: block;
    }
  }
  @media (max-width: ${variables.mobileBreakPoint}) {
    .qrcode,
    &::after {
      left: 0;
    }
  }
`;

3. 使用方式

// 引入组件
import Qrcode from "@/components/Qrcode";
// 使用
const address = "http://test-address?block=XXXX"
<Qrcode text={ address } />

4. 效果展示(pc端 / 移动端)

在这里插入图片描述
在这里插入图片描述


总结

下一篇讲【全局常用组件Echarts封装】。关注本栏目,将实时更新。

举报

相关推荐

0 条评论