【问题标题】:Function call in Material UI (React.js) not getting calledMaterial UI (React.js) 中的函数调用没有被调用
【发布时间】:2021-09-15 18:25:37
【问题描述】:
  • 今天开始用 Material UI 不知道为什么这个函数 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>
  );
}

【问题讨论】:

    标签: reactjs material-ui formsy-material-ui react-material-ui-form-validator react-material-ui-carousel


    【解决方案1】:

    您需要将按钮的类型设为submit 才能使用该按钮进行实际的表单提交。

          <Button
            className={classes.buttn}
            type="submit"
            variant="outlined"
            color="primary"
            align="left"
          >
            Register
          </Button>
    

    【讨论】:

    • 谢谢@Kavindu :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    相关资源
    最近更新 更多