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

相关推荐
前端布鲁伊几秒前
零代码上线一个图片处理网站,我是如何使唤AI干活的?
前端·ai编程
庄小焱1 分钟前
React——React基础语法(2)
前端·javascript·react.js
终端鹿4 分钟前
Vue3 核心 API 深度解析:ref / reactive / computed / watch
前端·javascript·vue.js
console.log('npc')11 分钟前
partial在react接口定义中是什么意思
前端·javascript·typescript
SuperEugene12 分钟前
前端 utils 工具函数规范:拆分 / 命名 / 复用全指南,避开全局污染等高频坑|编码语法规范篇
开发语言·前端·javascript
C澒15 分钟前
微前端容器标准化 —— 公共能力篇:通用请求
前端·架构
llxxyy卢24 分钟前
web部分中等题目
android·前端
若惜33 分钟前
selenium自动化测试web自动化测试 框架封装Pom
前端·python·selenium
Amumu121381 小时前
Js:内置对象
开发语言·前端·javascript
广州华水科技1 小时前
2026年单北斗GNSS变形监测系统推荐,助力精准监控与智慧城市建设
前端