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,但既然是以学习为目的最好是自己实现。

相关推荐
寅时码5 分钟前
我开源了一款 Canvas “瑞士军刀”,十几种“特效与工具”开箱即用
前端·开源·canvas
CF14年老兵7 分钟前
🚀 React 面试 20 题精选:基础 + 实战 + 代码解析
前端·react.js·redux
CF14年老兵8 分钟前
2025 年每个开发人员都应该知道的 6 个 VS Code AI 工具
前端·后端·trae
十五_在努力12 分钟前
参透 JavaScript —— 彻底理解 new 操作符及手写实现
前端·javascript
拾光拾趣录27 分钟前
🔥99%人答不全的安全链!第5问必翻车?💥
前端·面试
IH_LZH31 分钟前
kotlin小记(1)
android·java·前端·kotlin
lwlcode39 分钟前
前端大数据渲染性能优化 - 分时函数的封装
前端·javascript
Java技术小馆40 分钟前
MCP是怎么和大模型交互
前端·面试·架构
玲小珑44 分钟前
Next.js 教程系列(二十二)代码分割与打包优化
前端·next.js
coding随想1 小时前
HTML5插入标记的秘密:如何高效操控DOM而不踩坑?
前端·html