0

所以我专门为这个问题编写了这个反应小的反应形式,我想给它添加一个特性。

这是代码:

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>
  );
}

您会看到如果您没有填写其中一个输入,它将触发警报。但我想用焦点替换警报。因此,当我忘记填写某个输入时,它会专注于那个空输入,基本上是告诉我填写它。

先感谢您

4

4 回答 4

2

您可以使用钩子来实现这一点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>
);
}
于 2020-11-26T12:41:48.563 回答
1

您应该使用ref来访问一个元素,然后触发focus()它。有useRef钩子可以做到这一点。您的代码将是:

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>
  );
}

要了解有关ref阅读文档的更多信息。

于 2020-11-26T12:40:26.220 回答
0

你可以创建这样的东西,它使用 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();
}
}

此示例取自 react.org

于 2020-11-26T12:36:39.197 回答
-1

更新

经过一番深思熟虑,我想展示如何querySelector在 react 中正确使用,并在过程中简化示例:

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>
  );
}


您可以在事件中访问目标(表单),然后在其中查询以到达您正在寻找的元素,并将它们聚焦。在这种情况下不需要反应参考。请注意,通常不建议直接查询 DOM。文档确实将管理焦点指定为 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>
  );
}


于 2020-11-26T12:39:00.467 回答