1
  • 今天开始使用 Material UI 不知道为什么这个 Function handelSubmit() 没有被调用。控制台功能没有被调用,没有任何东西被打印出来。不知道我在哪里做错了,谢谢。
  • 我从表单标签调用该函数,也尝试从外部调用,但它不起作用。
import React, { useState } from 'react';
import Typography from '@material-ui/core/Typography';
import { Button, Container } from '@material-ui/core';
import { TextField } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';

const useStyle = makeStyles({
  field: { marginTop: 20, marginBottom: 20, display: 'block' },
});

export default function Create() {
  const classes = useStyle();
  const [name, setName] = useState('');
  const [phnNO, setPhnNo] = useState('');
  const [address, setAddress] = useState('');
  const [nameError, setnameError] = useState(false);
  const [phnNoError, setphnNOError] = useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    setnameError(true);
    setphnNOError(true);

    if (name == '') {
      setnameError(true);
    }
    if (phnNO == '') {
      setphnNOError(true);
    }
    if (name && phnNO && address) {
      console.log(name, phnNO, address);
    }
  };

  return (
    <form noValidate autoComplete="off" onSubmit={handleSubmit}>
      <TextField
        onChange={(e) => setName(e.target.value)}
        className={classes.field}
        label="Your Name"
        variant="outlined"
        color="secondary"
        fullWidth
        required
        error={nameError}
      />
      <TextField
        onChange={(e) => setPhnNo(e.target.value)}
        className={classes.field}
        label="Your mobile number"
        variant="outlined"
        color="secondary"
        fullWidth
        required
        error={phnNoError}
      />
      <TextField
        onChange={(e) => setAddress(e.target.value)}
        className={classes.field}
        label="Your address"
        multiline
        rows={4}
        variant="outlined"
        color="secondary"
        fullWidth
      />
      <Button
        className={classes.buttn}
        variant="outlined"
        color="primary"
        align="left">
        Register
      </Button>
    </form>
  );
}
4

1 回答 1

0

您需要具有按钮的类型submit才能使用按钮进行实际的表单提交。

      <Button
        className={classes.buttn}
        type="submit"
        variant="outlined"
        color="primary"
        align="left"
      >
        Register
      </Button>
于 2021-09-15T18:35:52.143 回答