【问题标题】:Please help to solve the problem React Hook "useRef"请帮助解决问题 React Hook "useRef"
【发布时间】:2021-09-17 04:09:46
【问题描述】:

您好请帮忙解决问题。

联系表格页面。

我必须从 useRef 获取数据到 const {name, email, message}。 而且我一定要使用 useRef

这是错误信息,我修复了照片错误页面:

src/components/Contact/Input.jsx 第 33:38 行:在函数“handleSubmit”中调用 React Hook “useRef”,该函数既不是 React 函数组件也不是自定义 React Hook 函数。 React 组件名称必须以大写字母 react-hooks/rules-of-hooks 开头

搜索关键字以了解有关每个错误的更多信息。

我该如何解决这个问题。

是源代码:

import React, { useState, useRef } from "react";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";

const useStyles = makeStyles((theme) => ({
  root: {
    "& > *": {
      margin: theme.spacing(1),
      width: "25ch",
    },
  },
}));

const Form = () => {
  const classes = useStyles();

  //

  const [status, setStatus] = useState("Submit");

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus("Sending...");


    const { name, email, message } = useRef("");
    let details = {
      name: name.value,
      email: email.value,
      message: message.value,
    };

    let response = await fetch("http://localhost:5000/contact", {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=utf-8",
      },
      body: JSON.stringify(details),
    });
    setStatus("Submit");
    let result = await response.json();
    alert(result.status);
  };

  //

  return (
    <div>
      <form className={classes.root} onSubmit={handleSubmit}>
        <TextField
          type="text"
          style={{ color: "white" }}
          inputRef={this.name}
          id="standard-basic"
          label="Name"
        />
        <TextField
          inputRef={this.email}
          required
          type="email"
          style={{ color: "white" }}
          id="standard-basic"
          label="Email"
        />
        <TextField
          inputRef={this.message}
          type="text"
          style={{ color: "white" }}
          id="standard-basic"
          label="Message"
          required
        />
        <Button type="submit" id="contacts1" color="primary">
          {status}
        </Button>
      </form>
    </div>
  );
};

export default Form;

这是错误页面:

【问题讨论】:

标签: javascript html reactjs


【解决方案1】:

我遇到了同样的问题,我是如何解决问题的:

  1. 您无需导入 React 即可使用 useRef。
  2. 只需将 useRef 导入为 UseRef 并使用它。
  3. 享受吧! :D

在你的情况下:

import { useState as UseState, useRef as UseRef } from "react";
.....
const { name, email, message } = UseRef("");

【讨论】:

  • 感谢您提供帮助,但尽管上述内容可能已经解决了您的个人问题,但这并不是问题的根本原因。完全可以按照上面原贴的方式导入useRef
猜你喜欢
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多