将自定义组件传递给打开它的材质ui对话框



我试图将一个自定义组件传递给MUI对话框,这样它就应该打开对话框本身并呈现它的子对话框。

const CustomDialog = ({children, someCustomComponent}) => {
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return(
<>
{someCustomComponent} // use this component to call handleOpen/handleClose
<Dialog>
<DialogTitle>
<DialogTItle>
<DialogContent>{children}</DialogContent>
<DialogActions>...</DialogActions>
</Dialog>
</>
);
}
CustomDialog.propTypes = {
someCustomComponent: PropTypes.node.isRequired,
}

然后这样命名

<CustomDialog someCustomComponent={<h1>open</h1>}>
{myDialogContent}
</CustomDialog>

这可能吗?本质上,我并不总是想要一个按钮来打开对话框。我想让我传递给它的任何组件都能打开它

这是通过使用Button

来实现的
return(
<>
<Button onClick={handleClickOpen} />
<Dialog>
...

但是我想传递任何元素给它

谢谢!

一个简单的方法是使用React.cloneElement

const CustomDialog = ({ children, someCustomComponent }) => {
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
// clone the component and add the onClick handler
const customComponentClone = React.cloneElement(someCustomComponent, {
onClick: handleClickOpen
});
return (
<>
{customComponentClone}
<Dialog>
<DialogTitle>
<DialogTItle>
<DialogContent>{children}</DialogContent>
<DialogActions>...</DialogActions>
</Dialog>
</>
);
}

这样你就可以像你提到的那样使用

<CustomDialog someCustomComponent={<h1>open</h1>}>
{myDialogContent}
</CustomDialog>

点击这里查看实时版本

最新更新