【问题标题】:Passing a custom component to material ui dialog that opens it将自定义组件传递给打开它的材料 ui 对话框
【发布时间】:2022-11-29 00:20:21
【问题描述】:

我正在尝试将自定义组件传递给 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>
   ...

但我想将任何元素传递给它。

谢谢!

【问题讨论】:

    标签: html reactjs material-ui


    【解决方案1】:

    一个简单的方法是使用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>
    

    在这里查看live version

    【讨论】:

      猜你喜欢
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多