react实现leaferjs编辑器功能点之右键点击菜单

实现功能:编辑器单个元素右键点击需要在鼠标位置出现菜单项

思路:leaferjs有右键点击事件,事件回调函数参数中有x和y坐标,那么在获得容器dom后可以直接使用绝对定位进行偏移

简化点:右键点击菜单不是出现的固定ui,因此使用多余变量进行维护一直是我不怎么喜欢的,并且声明式使用函数还需要传递各种参数,使用Context又难免耦合,因此我使用指令式组件封装针对x和y的一个组件,与leaferjs和要制作的编辑器无关。(指令式封装参考我的另一篇文章)

ts 复制代码
import React, { FC, useRef } from 'react';
import { useClickAway } from 'ahooks';
import { createPortal } from 'react-dom';
import { css } from '@emotion/css';
import { appInstance } from '@/runTime';
import { InstructionMountProps } from '@/hooks/useElementsContextHolder';

interface Props {
  container: HTMLDivElement
  x: number
  y: number
  node: React.ReactNode
}

const CoordinateDom: FC<Props & InstructionMountProps<null>> = (props) => {
  const { container, x, y, node, closeResolve } = props;
  const ref = useRef<HTMLDivElement>(null);

  useClickAway(() => {
    closeResolve();
  }, ref, ['click', 'contextmenu']);

  return (
    createPortal(
      <div ref={ref} className={css`position: absolute;left: ${x}px;top: ${y}px`}>
        {node}
      </div>,
      container,
    )
  );
};

export const openCoordinateDomPromise = (args: Props) => {
  return appInstance.getContextHolder().instructionMountPromise<Props, null>({
    Component: CoordinateDom,
    props: args,
  });
};

使用如下:

ts 复制代码
const rect_1 = Rect.one({
  editable: true,
  fill: '#FEB027',
  cornerRadius: [20, 0, 0, 20],
  zIndex: 2,
}, 100, 100);

rect_1.on(PointerEvent.MENU, (e) => {
  e.stop();
  openCoordinateDomPromise({
    container: this.containerRef.current,
    x: e.x,
    y: e.y,
    node: (
      <div className={css`width: 100px;height: 100px`}>1fefe24</div>
    ),
  });
});

简单封装如上,如菜单位置临界等问题以后在加相关处理逻辑,也可以使用antd的dropdown,但既然是以学习为目的最好是自己实现。

相关推荐
鹏多多12 小时前
解锁flutter弹窗新姿势:dialog-flutter_smart_dialog插件解读+案例
前端·flutter·客户端
IT_陈寒12 小时前
Redis 7.0的这个新特性让我处理百万级QPS轻松了50%,你可能还不知道!
前端·人工智能·后端
2301_7965125212 小时前
Rust编程学习 - 如何快速构建一个单线程 web server
前端·学习·rust
蒜香拿铁13 小时前
Angular【核心特性】
前端·javascript·angular.js
天天向上102413 小时前
vue3 css使用v-bind实现动态样式
前端·css·vue.js
艾小码13 小时前
前端新手必看!困扰90%人的10个JavaScript问题,一次性帮你解决
前端·javascript
xixixin_16 小时前
【React】为什么移除事件要写在useEffect的return里面?
前端·javascript·react.js
嘗_16 小时前
react 源码2
前端·javascript·react.js
我只会写Bug啊20 小时前
Vue文件预览终极方案:PNG/EXCEL/PDF/DOCX/OFD等10+格式一键渲染,开源即用!
前端·vue.js·pdf·excel·预览
扯蛋43821 小时前
LangChain的学习之路( 一 )
前端·langchain·mcp