如何在反应中添加过滤方法onclick按钮

How to add filter method onclick button in react

我有一个表单,其中包含名为 admissionNumber 的输入字段和按钮。在输入字段中,当用户输入数字并单击按钮时,函数 getAllStudent 将过滤一个数组。如果录取编号与输入的编号匹配,则其他字段(全名和教员)会自动填写。我怎样才能做到这一点 ?请有人帮我做这件事。谢谢

getAllStudents 函数 其中 return 学生详细信息(入学编号、全名、教师)

 getAllStudents(user._id, token).then((data) => {
  if (data.error) {
    setValues({ ...values, error: data.error });
  } else {
    setValues(data);
  }
});

表单域

<input
            type="text"
            onChange={(event) => {
              setSearchTerm(event.target.value);
            }}
            className="form-control offset-md-2  col-md-6"
            placeholder="Admission Number"
            required
            maxLength="5"
          />

          <button
            // onClick={}
            className="btn rounded ml-4"
            
          >
            Verify
          </button>
        </div>
        <div className="bg-dark rounded">Personal Details</div>
        <div className="row form-group ">
          <input
            type="text"         
            name="studentFullName"
            className="form-control mt-2 offset-md-2 col-md-8"
            placeholder="Student Name"
           
          />
          <input
            type="text"
            name="faculty"
            className="form-control mt-2 offset-md-2 col-md-8"
          />
        </div>

你应该将函数传递给按钮 onClick prop.

假设您使用功能组件和状态 studentscurrentUsersearchTerm你可以这样做:

const [students] = useState([...])

const [currentUser, setCurrentUser] = useState(undefined)

const [searchTerm, setSearchTerm] = useState(undefined)


const checkStudent = () => {
    const match = students.find(student  => student.admissionNumber === searchTerm)
    if(match) {
        setCurrentUser(match)
    }
}

return (
    <>
        <button
            onClick={() => checkStudent()}
        />

        <input
            type="text"         
            name="studentFullName"
            className="form-control mt-2 offset-md-2 col-md-8"
            placeholder="Student Name"
            value={currentUser?.fullname}
        />
    </>
)