【问题标题】:close React Dialog with a button使用按钮关闭 React 对话框
【发布时间】:2020-09-19 12:30:22
【问题描述】:

我想在访问屏幕时打开对话框,所以我将默认状态设置为 true。我做了一个自定义按钮。当我单击它时,状态应更改为 false 并且对话框应关闭。但是,对话框不会关闭。我做错了什么,我还能如何关闭对话框?

<Dialog open={openReminder}>
  <DialogTitle>Reminder</DialogTitle>
  <DialogContent>
    <DialogContentText>Don't forget to take your daily walk!</DialogContentText>
    <div className={classes.reminderContainer}>
      <DialogButton
        text={"Ok, thanks!"}
        onPress={() => setOpenReminder(false)}
      />
    </div>
  </DialogContent>
</Dialog>
export const DialogButton = ({ onPress, text }) => {
  const classes = useStyles();
  return (
    <Button onPress={onPress} className={classes.button}>
      {text}
    </Button>
  );
};

【问题讨论】:

  • 您是否尝试使用onPress 作为 DialogBu​​tton 中的道具?你能从这个组件中添加你的代码吗?
  • 你的意思是onClick而不是onPress
  • 将它与 React Native 混合,哎呀@NearHuscarl

标签: javascript reactjs typescript dialog material-ui


【解决方案1】:

问题在于 onPress 事件尝试使用 onClick,

 <Button onClick={onPress} className={classes.button}>
  {text}
</Button>

【讨论】:

    【解决方案2】:

    我注意到的两件事:

    1. 您需要像这样将 onPress 更改为 OnClick :

      <Button onClick={onPress} className={classes.button}>
       {text}
      </Button>
      
    2. 在 Dialog 组件内部检查是否在 'open' 属性设置为 false 时显式隐藏它。

    【讨论】:

      【解决方案3】:
      <DialogButton text={"Ok, thanks!"} onPress={()=>setOpenReminder(!openReminder)}/>
      
      <Button onClick={onPress} className={classes.button}>
       {text}
      </Button>
      

      【讨论】:

      • 更改 setOpenReminder(!openReminder)} 以便反之亦然 (true/false) 并在按钮中使用 onClick 事件。它会起作用的。
      【解决方案4】:

      像这样在您的子组件中使用 onClick 更改 onPress。

      <Button onClick={onPress} className={classes.button}>
            {text}
      </Button>
      

      检查它是否有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-15
        • 2015-02-12
        相关资源
        最近更新 更多