【问题标题】:How to add filter method onclick button in react如何在反应中添加过滤方法onclick按钮
【发布时间】:2021-04-26 01:31:12
【问题描述】:

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

getAllStudents 函数,返回学生详细信息(admissionNumber、fullname、faculty)

 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>

【问题讨论】:

    标签: node.js reactjs filter mongoose-schema


    【解决方案1】:

    你应该将一个函数传递给按钮onClickprop。

    假设您使用功能组件和具有 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}
            />
        </>
    )
    

    【讨论】:

      猜你喜欢
      • 2021-11-12
      • 2020-12-22
      • 1970-01-01
      • 2013-12-13
      • 2012-07-29
      • 2022-08-23
      • 2021-03-25
      • 2013-11-06
      • 1970-01-01
      相关资源
      最近更新 更多