22

基于TypeScript与React Hooks开发的通用组件库

 4 years ago
source link: https://juejin.im/post/5e34fe4ee51d4557e632f143
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
2020年02月01日 阅读 2006

基于TypeScript与React Hooks开发的通用组件库

项目地址(欢迎star):react-draggable-layer

技术博客:www.linxiangjun.com

2019年以来,越来越多的公司与项目都选择使用强类型语言TypeScript作为主要语言,可以预见的是2020年TypeScript将成为前端开发所需要具备的能力之一。

目前前端工程师使用最多的无疑问是微软开源的VSCode,它本身提供的功能并不多,但是通过支持插件的方式使得其具备了IDE的强大能力。同时,VSCode是使用TypeScript基于Eletron开发的,使得它对于TypeScript的支持非常的强大。如果你使用的编辑器是VSCode,那么项目中完全使用TypeScript编程将会大大的提高编程效率,甚至使用一段时间后你会发现,已经渐渐离不开TypeScript。

应用新的语言还是语法都会面临着许多困难和陷阱,这个时候如果能够参考一些现成的写法肯定会带来收益。这也是我写这篇文章的初衷。

下面是react-draggable-layer使用到的一些技术细节:

  • TypeScript
  • React Hooks
  • React Portals
  • emotion
  • Babel
效果动画

Portals

实现一个弹层类组件,React提供了Portals方法,能够将子节点渲染到存在于父组件以外的DOM节点上。我们先实现一个封装了Portals方法的通用组件:

components/Portal.jsx

import React, { useEffect, useRef } from "react";
import ReactDOM from "react-dom";

interface PortalProps {
  children: React.ReactElement;
}

const Portal: React.FC<PortalProps> = props => {
  // 使用useRef创建ref对象,可以用来保存节点
  const { current: el } = useRef(document.createElement("div"));

  // 等同于类组件的componentDidMount方法
  useEffect(() => {
    const root = document.getElementById("root");
    if (root) {
      root.appendChild(el);
    }

    // 组件销毁后记得移除div
    return () => {
      if (root) {
        root.removeChild(el);
      }
    };
  }, []);

  return ReactDOM.createPortal(props.children, el);
};

export default Portal;

复制代码

css-in-js

有了Portal组件之后在可拖拽弹层组件中引入,这样组件在使用时就可以挂载到root节点下。在组件中样主要是以css-in-js的方式来实现的,它的优点有:

  1. 不需要引入css样式文件或者css预处理器
  2. 可避免因为样式名冲突带来的全局污染问题
  3. 不需要各种繁琐的命名规则

这并不是说它就没有缺点的,同样的,使用css-in-js来开发会使得很多高阶css用法非常的复杂,所以需要根据项目情况来辩证的思考与选择。不过对于此项目来说css-in-js就非常的合适,它使得我们可以将更多的精力放在组件化上面。另外这里推荐下emotion这个库。

React.FC

这里先来基于项目说一下TypeScript开发React函数式组件的规范:

interface DraggableLayerProps {
  children?: React.ReactElement;
  titleName?: string;
  visible?: boolean;
  onClose?: () => void;
}

const DraggableLayer: React.FC<DraggableLayerProps> = props => <Component />

export default DraggableLayer
复制代码

使用函数式组件时需要将组件申明为React.FC类型,也就是Functional Component的意思,另外props需要申明各个参数的类型,然后通过泛型传递给React.FC

draggable

可拖拽功能的实现是基于实时计算组件x轴与y轴的距离来实现的,具体代码比较简洁:

let initX = 0;
let initY = 0;
let isMouseDown = false;

const handleMouseDown = (e: MouseEvent) => {
    isMouseDown = true;
    initX = e.offsetX;
    initY = e.offsetY;
    draggableRef.current.style.opacity = 0.5;
  };

  const handleMouseMove = (e: MouseEvent) => {
    if (isMouseDown) {
      const x = e.clientX - initX;
      const y = e.clientY - initY;
      draggableRef.current.style.left = `${x}px`;
      draggableRef.current.style.top = `${y}px`;
    }
  };

  const handleMouseUp = () => {
    isMouseDown = false;
    if (draggableRef && draggableRef.current) {
      draggableRef.current.style.opacity = 1;
    }
  };
复制代码

在组件获取props时有很多可选的参数,比如titleName,因为使用了TypeScript,所以对可选参数进行赋值操作时提示错误信息,这点在开发时能够有效的避免出错。另外,组件销毁后需要在useEffectreturn回调函数中清除绑定的event。这些细节需要注意。

非常欢迎尝试本项目,可以直接使用npm install react-draggable-layer来使用,有好的建议也希望能够收到提交的issues。一些更加详细的使用说明在项目中的README文件中。如果本文或者项目对你有帮助的话,非常高兴您能够点下star支持。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK