简体   繁体   English

我如何将输入集中在反应表单中以进行表单验证

[英]how do i focus an input in react form for form validation

So I've coded this react small react form specifically for this question and I want to add a feature to it.所以我专门为这个问题编写了这个反应小的反应形式,我想给它添加一个特性。

Here's the code:这是代码:

import React, { useState } from "react";

export default function App() {
  const [formInfo, setFormInfo] = useState({ name: "", email: "" });

  function onch(e) {
    const { value, id } = e.target;

    id === "name"
      ? setFormInfo({ ...formInfo, name: value })
      : setFormInfo({ ...setFormInfo, email: value });
  }

  function onsub(e) {
    e.preventDefault();

    const { name, email } = formInfo;

    if (name === "") {
      alert("fill your name");
    } else if (email === "") {
      alert("fill out your email");
    } else {
      alert("done");
      setFormInfo({ name: "", email: "" });
    }
  }

  const { name, email } = formInfo;

  return (
    <form action="" onSubmit={onsub}>
      <div className="input">
        <label htmlFor="">Name</label>
        <input type="text" name="" id="name" onChange={onch} value={name} />
      </div>
      <div className="input">
        <label htmlFor="">E-mail</label>
        <input type="text" name="" id="email" onChange={onch} value={email} />
      </div>

      <div className="input">
        <button type="submit">Submit</button>
      </div>
    </form>
  );
}

You see if you didn't fill out one of the inputs it will trigger an alert.您会看到如果您没有填写其中一个输入,它将触发警报。 But I want to replace the alert with focus instead.但我想用焦点替换警报。 So when I forgot to fill out a certain input it will focus on that empty input basically telling me to fill it out.因此,当我忘记填写某个输入时,它会专注于那个空输入,基本上是告诉我填写它。

THANK YOU IN ADVANCE先感谢您

You should use ref to get access to an element and then trigger focus() for it.您应该使用ref来访问一个元素,然后为它触发focus() There is useRef hook to do this.useRef钩子可以做到这一点。 Your code will be:您的代码将是:

import React, { useState, useRef } from "react";

export default function App() {
  const [formInfo, setFormInfo] = useState({ name: "", email: "" });
  const nameRef = useRef();
  const emailRef = useRef();

  function onch(e) {
    const { value, id } = e.target;

    id === "name"
      ? setFormInfo({ ...formInfo, name: value })
      : setFormInfo({ ...setFormInfo, email: value });
  }

  function onsub(e) {
    e.preventDefault();

    const { name, email } = formInfo;

    if (name === "") {
      nameRef.current.focus();
    } else if (email === "") {
      emailRef.current.focus();
    } else {
      alert("done");
      setFormInfo({ name: "", email: "" });
    }
  }

  const { name, email } = formInfo;

  return (
    <form action="" onSubmit={onsub}>
      <div className="input">
        <label htmlFor="">Name</label>
        <input
          type="text"
          name=""
          id="name"
          onChange={onch}
          value={name}
          ref={nameRef}
        />
      </div>
      <div className="input">
        <label htmlFor="">E-mail</label>
        <input
          type="text"
          name=""
          id="email"
          onChange={onch}
          value={email}
          ref={emailRef}
        />
      </div>

      <div className="input">
        <button type="submit">Submit</button>
      </div>
    </form>
  );
}

To learn more about ref read documentation .要了解有关ref的更多信息,请阅读文档

You can achieve this using useRef hook, the code with give the focus to the first empty element and make its borders red您可以使用useRef钩子来实现这一点,代码将焦点放在第一个空元素上并使其边框变为红色

 import React, { useState, useRef } from "react";

 export default function App() {
 const [formInfo, setFormInfo] = useState({ name: "", email: "" });

function onch(e) {
const { value, id } = e.target;

id === "name"
  ? setFormInfo({ ...formInfo, name: value })
  : setFormInfo({ ...setFormInfo, email: value });
}

const nameRef = useRef();
const emailRef = useRef();

function onsub(e) {
e.preventDefault();

const { name, email } = formInfo;

if (name === "") {
  nameRef.current.focus();
  nameRef.current.style.border = "1px solid red";
} else if (email === "") {
  nameRef.current.focus();
  nameRef.current.style.border = "1px solid red";
} else {
  alert("done");
  setFormInfo({ name: "", email: "" });
}
}

const { name, email } = formInfo;

return (
<form action="" onSubmit={onsub}>
  <div className="input">
    <label htmlFor="">Name</label>
    <input
      ref={nameRef}
      type="text"
      name=""
      id="name"
      onChange={onch}
      value={name}
    />
  </div>
  <div className="input">
    <label htmlFor="">E-mail</label>
    <input
      ref={emailRef}
      type="text"
      name=""
      id="email"
      onChange={onch}
      value={email}
    />
  </div>

  <div className="input">
    <button type="submit">Submit</button>
  </div>
</form>
);
}

You can create something like this which use createRef() api of react.您可以使用 createRef() api 的反应创建类似的东西。

class MyComponent extends React.Component {
constructor(props) {
super(props);

this.inputRef = React.createRef();
}

render() {
return <input type="text" ref={this.inputRef} />;
}

componentDidMount() {
this.inputRef.current.focus();
}
}

This sample is taken from react.org此示例取自 react.org

Updated更新

After some deliberations, I wanted to showcase how to use querySelector in react correctly, and in the process simplify the example:经过一番深思熟虑,我想展示如何正确使用querySelector做出反应,并在此过程中简化示例:

import React, { useCallback, useRef } from "react";

export default function App() {
  const formRef = useRef(null);

  const handleSubmit = useCallback((e) => {
    e.preventDefault();

    const formData = new FormData(e.target);

    for (let [name, value] of formData.entries()) {
      if (!value) {
        formRef.current.querySelector(`input[name=${name}]`).focus()
        break
      }
    }
    // do something with the formData
  }, []);

  return (
    <form ref={formRef} action="" onSubmit={handleSubmit}>
      <div className="input">
        <label htmlFor="">Name</label>
        <input type="text" name="name" id="name" />
      </div>
      <div className="input">
        <label htmlFor="">E-mail</label>
        <input type="text" name="email" id="email" />
      </div>

      <div className="input">
        <button type="submit">Submit</button>
      </div>
    </form>
  );
}


you can access the target (the form) in the event, and then query inside it to reach the element you're looking for, and focus them.您可以在事件中访问目标(表单),然后在其中查询以到达您正在寻找的元素,并将它们聚焦。 No need for react ref in this case.在这种情况下不需要反应参考。 Do note, it is usually not recommended to query the DOM directly.请注意,通常不建议直接查询 DOM。 The docs do specify managing focus as an intended use for refs, as seen here文档确实将管理焦点指定为 refs 的预期用途,如此处所示

import React, { useState } from "react";
import "./styles.css";

export default function App() {

  const [formInfo, setFormInfo] = useState({name: '', email: ''})


  function onch(e){
    const {value, id} = e.target

    id === 'name' ? setFormInfo({...formInfo, name: value}) : setFormInfo({...setFormInfo, email: value})

  }

  function onsub(e){
    e.preventDefault()

    const {name, email} = formInfo
    
    if(name === ''){
      e.target.querySelector('#name').focus()
    }
    else if(email === ''){
      e.target.querySelector('#email').focus()
    }else{
      alert('done')
      setFormInfo({name: '', email: ''})
    }
    
  }

  const {name, email} = formInfo

  return (
  <form action="" onSubmit={onsub}>

    <div className="input">
      <label htmlFor="">Name</label>
      <input type="text" name="" id="name" onChange={onch} value={name}/>
    </div>
    <div className="input">
      <label htmlFor="">E-mail</label>
      <input type="text" name="" id="email" onChange={onch} value={email}/>
    </div>
   
    <div className="input">
      <button type="submit">Submit</button>
    </div>

  </form>
  );
}


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

相关问题 如何在反应中进行表单验证? - How to do form validation in react? 如何使用 React-bootstrap 进行多输入表单验证? - How to do Multiple Input form Validation with React-bootstrap? 如何在表单输入工作中进行 javascript 验证? - How do I get javascript validation on form input working? 如何向我的 React 组件中的表单添加验证? - How do I add validation to the form in my React component? 如何对此进行适当的验证并设置焦点,然后提交表单 - How to do proper validation for this and set focus and then form has to submitted 如何根据焦点更改类并更改 React 中的输入表单 - How to change a class based on focus and change in an input form in React 如何简化这段 React 代码? (渐进式输入形式) - How do I simplify this piece of React code? (Progressive input form) 如何在 html 表单输入元素上模拟事件(焦点和模糊除外)? - How do I simulate events (other than focus and blur) on an html form input element? 当远离提交按钮时,如何将焦点设置在表单中的第一个输入上? - How do I set the focus on the first input in a form when blurring away from the submit button? 如果用户专注于登录输入,如何在输入密钥时提交表单? - How do I get the form to submit on enter key only when user has focus on login input?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM