如何使用材料Ui与打字稿反应

时间:2020-09-01 19:24:16

标签: reactjs typescript material-ui react-hooks

这是我的代码,它可以正常工作,但是我想使用它的材料ui。但是例如当我使用TextField而不是输入时,我得到了错误

Uncaught (in promise) Error: Request failed with status code 422
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:69)

我安装了材料ui的npm软件包,并导入了TextField,然后使用它代替了输入。

所以我不明白这里出了什么问题?有人可以帮忙吗?

import * as React from "react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import TextField from "@material-ui/core/TextField";

import axios from "axios";

import "./App.css";

type FormData = {
  first: string;
  infix: string;
  last: string;
  email: string;
  message: string;
};
function App() {
  const { register, handleSubmit } = useForm<FormData>();
  const [first, setVoor] = useState("");
  const [infix, setTussen] = useState("");
  const [last, setAchter] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");

  const onSubmit = handleSubmit(({ first, infix, last, email }) => {
    setVoor(first);
    setTussen(infix);
    setAchter(last);
    setEmail(email);

    axios
      .post(" https://code-application-api.devheld.nl/registration", {
        first,
        infix,
        last,
        email,
      })
      .then((res) => {
        console.log(res.data, "data?");
        setMessage(res.data.message);
      });
  });

  return (
    <form onSubmit={onSubmit}>
     <TextField name="first" ref={register} label="voornaam" />
      <label style={{ color: "black" }}>Tussenvoegsel</label>
      <input name="infix" ref={register} />
      <label style={{ color: "black" }}>Achternaam</label>
      <input name="last" ref={register} />
      <label style={{ color: "black" }}>E-mail</label>
      <input name="email" ref={register} />

      <input type="submit" />

      <p>{first}</p>
      <p>{infix}</p>
      <p>{last}</p>
      <p>{email}</p>
      {message && <p>{message}</p>}
    </form>
    // <p>{Object.keys(email)}</p>
  );
}

export default App;

1 个答案:

答案 0 :(得分:-1)

您需要注意一些事项并进行一些配置。 Material-UI Documentation