Диалоговое окно не нажимает на событие onClick - PullRequest
1 голос
/ 21 июня 2019

У меня есть следующий код, который я использую в качестве учебника:

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;

После нажатия кнопки диалоговое окно не открывается, а страница обновляется. Я не уверен, что здесь происходит.

1 Ответ

3 голосов
/ 21 июня 2019

Страница обновляется, так как тип кнопки - «отправить», что вызывает обновление страницы.

Вы можете подписаться, нажав на «Песочницу». Edit so.answer.56695455

Таким образом, вы можете остановить проблему двумя различными способами.

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>
  );
};

Ознакомьтесь с рабочей демонстрацией ниже.demo

2 Запретить событие по умолчанию при нажатии кнопки.

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

Если вам нужно сохранить type="submit" для кнопки, вы можете предотвратить обновлениеиспользуя событие, переданное обратному вызову onClick и вызову .preventDefault().

enter image description here

...