import React, { CSSProperties, useEffect, useRef, useState } from "react"; import ContextMenuFC from "./context-menu-fc"; import './context-menu-wrapper.less' interface Iprops { visible?: boolean width?: number height?: number children?: React.ReactNode container?: React.ReactNode closable?: boolean onVisibleChange?: (visible: boolean) => void maskStyle?: CSSProperties wrapperClassname?: string disabled?: boolean } function ContextMenuWrapper(props: Iprops) { // const [height, setHeight] = useState(300); const [left, setLeft] = useState(0); const [top, setTop] = useState(0); const [visible, setVisible] = useState(false); const ref = useRef(); const childrenRef = useRef(); const width = props.width; const onTrigger = () => { if (props.disabled) return; if (props.onVisibleChange) { if (props.visible != null) { props.onVisibleChange(!props.visible); } else { props.onVisibleChange(!visible) setVisible(!visible); } } else { setVisible(!visible); } } useEffect(() => { let ele = ref.current; if (ele == null) return; let bound = ele.getBoundingClientRect(); let clientX = bound.left + bound.width / 2 - width / 2; let bodyW = document.body.clientWidth; if (clientX + width > bodyW) { clientX = bound.right - width; } setLeft(clientX); let clientY = bound.bottom; let bodyH = document.body.clientHeight; // if (!!childrenRef.current) { // let height = childrenRef.current.getBoundingClientRect().height; // if (clientY + height > bodyH) { // clientY = bound.top - height; // } // } let height = props.height; if (clientY + height > bodyH) { clientY = bound.top - height - 6; } else { clientY +=6 } setTop(clientY); }, [props.visible, visible]) return (
{props.container}
{props.children}
) } ContextMenuWrapper.defaultProps = { width: 250, closable: true, } export default ContextMenuWrapper;