[英]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.