【问题标题】:Dialog box doesn't click on onClick event对话框没有点击 onClick 事件
【发布时间】:2019-06-21 00:29:50
【问题描述】:

我将以下代码用作教程:

CommentSend.js

import React, { useState } from "react";
import Dialog from "@material-ui/core/Dialog";
import FormControl from "@material-ui/core/FormControl";
import Button from "@material-ui/core/Button";
import Input from "@material-ui/core/Input";
import InputLabel from "@material-ui/core/InputLabel";

const CommentSend = () => {
  const [description, setDescription] = useState("");
  const [open, setOpen] = useState(false)

  return (                                 
              <form>                                    
                  <Button            
                    onClick={() => setOpen(true)}        
                    type="submit"    
                  >
                      Add Comment
                  </Button>
                  <Dialog
                    open={open}
                  >
                    <FormControl fullWidth>
                      <InputLabel htmlFor="comment">Comment</InputLabel>
                      <Input
                        id="comment"
                        onChange={event => setDescription(event.target.value)}
                      />                      
                    </FormControl>
                  </Dialog>
              </form>
          );}

export default CommentSend;

点击按钮后,对话框没有打开,而是页面刷新。我不确定这里发生了什么。

【问题讨论】:

  • 您的按钮是submit 类型,这意味着当您单击它时表单将提交。表单提交,提交网页(又名页面刷新)。而是为按钮指定不同的类型(如&lt;button type="button")。您也应该在表单元素上添加onSubmit

标签: reactjs material-ui


【解决方案1】:

页面正在刷新,因为按钮的类型是“提交”,触发页面刷新。

您可以通过分叉 Sandbox 来跟进。

因此,您可以通过两种不同的方式解决问题。

1 删除“type=submit”

const CommentSend = () => {
  // ... redacted for brevity    
  return (
    <form>
      <Button
        onClick={e => {
          setOpen(true);
        }}
      >
        Add Comment
      </Button>
      <Dialog open={open}>
         // ... redacted for brevity
      </Dialog>
    </form>
  );
};

查看下面的工作演示。

2 防止默认按钮单击事件。

 <Button
    onClick={e => {
      e.preventDefault();
      setOpen(true);
    }}
    type="submit"
  >

如果您需要保留按钮的type="submit",您可以使用传递给“onClick”回调的事件并调用.preventDefault() 来阻止刷新。

【讨论】:

  • 很好的答案和解释!如果其目的不是提交,您还可以将按钮类型更改为提交以外的其他内容。但这只是一个挑剔的小点哈哈:D +1
  • 伟大的收获@JohnRuddell 明确type="button" 是一个更好的主意,然后出于可访问性原因放弃或离开“type='submit'” - developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多