防止非回车键触发提交功能

发布于 2025-01-14 05:42:26 字数 2170 浏览 0 评论 0原文

我正在使用反应组件系统(mantine)。我有一个选择字段,我想使用任意键选择一个选项,然后仅使用回车键提交。

现在的问题是,一旦出现下拉列表并且我按任意键,它就会调用该函数并发送我设置的空字符串。如果表单中没有提交按钮,onSubmit 将无法工作,将显示设置为没有仍然无法提交。所以,我就得到了这个结果。

import React, { useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { Text, Select } from "@mantine/core";
import { Icon } from "@iconify/react";
import axios from "axios";
import { api } from "../helpers/api";

const Home = () => {
  const [joblist, setJoblist] = React.useState("");
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const history = useNavigate();
  const selectForm = useRef(null);
  function handleSubmit(e) {
    if (e.key === "Enter" && e.preventDefault()) {
      selectForm.current.submit();
    }

    setJoblist("");
    console.log(joblist);
    setLoading(true);
    const uu = {
      jobs: joblist,
    };
    console.log(uu);
    console.log(api.jobs);
    fetch(api.jobs, {
      method: "POST",
      headers: {
        "Access-Control-Allow-Origin": "http://127.0.0.1:8000/",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(uu),
    })
      .then((res) => {
        console.log(res.data);
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
        setError(err.message || err);
      });
  }

  return (
    <div>
    
      <form ref={selectForm} onKeyDown={handleSubmit}>
        <Select
          label="Your favorite framework/library"
          placeholder="Pick one"
          searchable
          clearable
          nothingFound="No options"
          value={joblist}
          onChange={setJoblist}
          data={[
            { value: "react", label: "React" },
            { value: "ng", label: "Angular" },
            { value: "svelte", label: "Svelte" },
            { value: "vue", label: "Vue" },
          ]}
          style={{
            width: "608px",
            marginLeft: "294px",
            marginTop: "-100px",
          }}
        />
      </form>
    </div>
  );
};

export default Home;

I am using a react components system(mantine). I have a select field and I want to select an option with any key and submit using the enter key only.

The problem right now is that once the dropdown appears and I press any key it calls the function and sends the empty string i set. The onSubmit won't work without a submit button present in the form, setting display as none still didn't get it to submit. So, I resulted to this.

import React, { useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { Text, Select } from "@mantine/core";
import { Icon } from "@iconify/react";
import axios from "axios";
import { api } from "../helpers/api";

const Home = () => {
  const [joblist, setJoblist] = React.useState("");
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const history = useNavigate();
  const selectForm = useRef(null);
  function handleSubmit(e) {
    if (e.key === "Enter" && e.preventDefault()) {
      selectForm.current.submit();
    }

    setJoblist("");
    console.log(joblist);
    setLoading(true);
    const uu = {
      jobs: joblist,
    };
    console.log(uu);
    console.log(api.jobs);
    fetch(api.jobs, {
      method: "POST",
      headers: {
        "Access-Control-Allow-Origin": "http://127.0.0.1:8000/",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(uu),
    })
      .then((res) => {
        console.log(res.data);
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
        setError(err.message || err);
      });
  }

  return (
    <div>
    
      <form ref={selectForm} onKeyDown={handleSubmit}>
        <Select
          label="Your favorite framework/library"
          placeholder="Pick one"
          searchable
          clearable
          nothingFound="No options"
          value={joblist}
          onChange={setJoblist}
          data={[
            { value: "react", label: "React" },
            { value: "ng", label: "Angular" },
            { value: "svelte", label: "Svelte" },
            { value: "vue", label: "Vue" },
          ]}
          style={{
            width: "608px",
            marginLeft: "294px",
            marginTop: "-100px",
          }}
        />
      </form>
    </div>
  );
};

export default Home;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

∞琼窗梦回ˉ 2025-01-21 05:42:26

if (e.key === "Enter" && e.preventDefault()) {
  selectForm.current.submit();
}

e.key === "Enter" 为 false 时,条件评估将立即停止。
所以尝试一下:

e.preventDefault()
if (e.key === "Enter") {
  selectForm.current.submit();
}

你可能需要这个来阻止执行代码的其余部分(但这还不清楚......)

else {
  return
}

With

if (e.key === "Enter" && e.preventDefault()) {
  selectForm.current.submit();
}

When e.key === "Enter" is false, the condition evaluation stops right there.
So try:

e.preventDefault()
if (e.key === "Enter") {
  selectForm.current.submit();
}

And you may need this to prevent executing the rest of the code (but that is unclear...)

else {
  return
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文