繁体   English   中英

反应输入字段“必需”不起作用

[英]React input field "required" does not work

我正在使用 materializecss 作为我的输入样式。 我在输入字段中添加了 required 。 但是我仍然可以不写任何东西就提交表格。 React 是否更改了“必需”选项,因为我的其他项目“需要”它工作正常。

import React from "react";
import { createLogEntry } from "./Api";
import Show from "./Show";
export default function Form() {
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState("");
  const [state, setState] = React.useState({
    name: " ",
    description: " "
  });

  const changeHandler = e => {
    setState({ ...state, [e.target.id]: e.target.value });
  };
  const handleSubmit = async e => {
    e.preventDefault();
    setLoading(true);
    try {
      await createLogEntry({
        name: state.name,
        description: state.description
      });
    } catch (error) {
      setError(error.message);
    }
    setLoading(false);
    setState({ name: " ", description: " " });
  };
  return (
    <React.Fragment>
      <div className="app">
        <div className="row">
          <form className="col s12" onSubmit={handleSubmit}>
            {error ? <p className="error">{error}</p> : null}
            <div className="row">
              <div className="input-field col s3">
                <input
                  id="name"
                  type="text"
                  data-length="4"
                  onChange={changeHandler}
                  value={state.name}
                  required //This is where I mentioned mandatory
                />
                <label htmlFor="input_text">Topic</label>
              </div>
            </div>
            <div className="row">
              <div className="input-field col s8">
                <textarea
                  id="description"
                  className="materialize-textarea"
                  data-length="120"
                  onChange={changeHandler}
                  value={state.description}
                  required //This is where I mentioned mandatory
                ></textarea>
                <label htmlFor="textarea2">Description</label>
              </div>
            </div>
            <button
              className="btn waves-effect blue lighten-1"
              type="submit"
              name="action"
              disabled={loading}
            >
              {loading ? "Loading..." : "Create Entry"}
            </button>
          </form>
        </div>
      </div>
      <Show />
    </React.Fragment>
  );
}

忽略此消息。 我无法在 Stack Overflow 上上传这篇文章,因为它说我的代码多于详细信息:)。

表单字段值的默认状态应该是一个空字符串,而您正在设置一个空格:

 const [state, setState] = React.useState({
    name: " ", // There is an extra space here
    description: " " // And here
  });

只需删除空格,默认表单验证就可以工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM