【问题标题】:React: Prevent MUI Draggable Dialog From Going Off ScreenReact:防止 MUI 可拖动对话框离开屏幕
【发布时间】:2022-03-15 14:42:38
【问题描述】:

我正在使用 MUI 库,特别是看到 here 的 Draggable Dialog 组件。

我的问题是如何阻止对话框被拖出屏幕?

我已经在 Paper 组件中尝试过这个,但它不起作用:

import * as React from 'react';
import Paper, { PaperProps } from '@mui/material/Paper';
import Draggable, { DraggableEvent, DraggableData } from 'react-draggable';
export const PaperComponent = (props: PaperProps) => {
  const widgetContainerRef = React.useRef<HTMLInputElement>(null);
  const [widgetState, setWidgetState] = React.useState({
    visible: false,
    disabled: true,
    bounds: { left: 0, top: 0, bottom: 0, right: 0 },
  });
  // const draggleRef = useRef<HTMLInputElement>(null);
  const onStart = (event: DraggableEvent, uiData: DraggableData) => {
    const { clientWidth, clientHeight } = window?.document?.documentElement;
    const targetRect = widgetContainerRef?.current?.getBoundingClientRect();
    if (targetRect) {
      setWidgetState((prevState) => ({
        ...prevState,
        bounds: {
          left: -targetRect?.left + uiData?.x,
          right: clientWidth - (targetRect?.right - uiData?.x),
          top: -targetRect?.top + uiData?.y,
          bottom: clientHeight - (targetRect?.bottom - uiData?.y),
        },
      }));
    }
  };
  return (
    <Draggable
      handle="#draggable-dialog-title"
      cancel={'[class*="MuiDialogContent-root"]'}
      nodeRef={widgetContainerRef}
      onStart={(event, uiData) => onStart(event, uiData)}
    >
      {/* <Resizable height={scaler.height} width={scaler.width} onResize={onResize}> */}
      <div ref={widgetContainerRef}>
        <Paper {...props} />
      </div>
    </Draggable>
  );
};

有人知道如何防止我的用户将对话框拖出屏幕吗?

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    看起来我在这里忽略了一点。如果你添加它就可以了:

    <Draggable
    ...
    bounds={widgetState.bounds}
    >
    <div ref={widgetContainerRef}>
      <Paper {...props} />
     </div>
    </Draggable>
    

    【讨论】:

      【解决方案2】:

      使用onDrag Prop防止被拖拽,具体场景返回false

            onDrag={(e: any) => {
              const from = e.relatedTarget || e.toElement;
              if (!from || from.nodeName === EVENT_NODE_NAME.HTML) {
                // stop your drag event here
                return false;
              }
            }}
            handle='#event-max-dialog'
            cancel={'[class*="MuiDialogContent-root"]'}>```
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-22
        • 2017-12-13
        相关资源
        最近更新 更多