这是可能的,而且没有太多麻烦!当对话框打开时,它的根容器是一个类为MuiDialog-root 的div,直接在你的<body> 中生成。我们没有将 react-draggable 组件放在对话框的 PaperComponent 周围,而是将其放在整个对话框周围:
<Draggable
handle={'[class*="MuiDialog-root"]'}
cancel={'[class*="MuiDialogContent-root"]'}>
<Dialog
// Styling goes here
>
... // Dialog contents
</Dialog>
</Draggable>
然后,有必要对 Dialog 进行一些样式设置。我们需要确保禁用背景,然后缩小容器大小,这样当我们在它后面点击时,我们实际上是在选择其他组件:
<Dialog
open={open}
onClose={handleClose}
disableEnforceFocus // Allows other things to take focus
hideBackdrop // Hides the shaded backdrop
disableBackdropClick // Prevents backdrop clicks
PaperComponent={PaperComponent}
style={{
top: '30%', // Position however you like
left: '30%',
height: 'fit-content', // Ensures that the dialog is
width: 'fit-content', // exactly the same size as its contents
}}
>
...
</Dialog>
注意PaperComponent 属性。根据可拖动对话框上的material-ui docs,这是指包含对话框内容的表面。但是,我们需要创建此组件以进行样式设置,而不是将纸张包装在 <Draggable> 中。如果我们不这样做,PaperComponent 将有很大的、令人讨厌的边距,并且不能正确地适应它的父级。
function PaperComponent(props: PaperProps) {
// PaperProps is an import from '@material-ui/core'
return (
<Paper {...props} style={{ margin: 0, maxHeight: '100%' }} />
);
}
请务必将此函数放置在渲染组件之外。否则,每次状态更改时,您的对话框内容都会重新加载。这对我来说很糟糕,因为我在对话框中使用了自动完成字段,并且每次我选择一个选项并使用 onChange() 执行某些操作时,文本输入都会消失。更改函数范围解决了这个问题。