使用输入在反应中按名称搜索过滤器

search filter by name in react using input

我有 table 个用户,我必须 filter/search 个输入名称的用户。例如,当键入 John 时,我必须在 table.

中列出所有名为 John 的用户

Table 所有用户代码

ListPatients.js

const ListPatients = ({ pacientes, setPacientes }) => {

  const removePaciente = (idToDelete) => {
    const newTasks = [...pacientes];
    newTasks.splice(idToDelete, 1);
    setPacientes(newTasks);
  };
  return (
    <div style={{ display:"flex", alignItems:"center", flexDirection:'column'}}>
      <h1>List</h1>
      <Table style={{ border:'1'}}>
        <thead>
          <tr style={{padding:'0 1rem'}}>
            <th>Name</th>
            <th>Birth date</th>
            <th>CPF</th>
            <th>Gender</th>
            <th>Addres</th>
            <th>Status</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {pacientes.length > 0 ? (
            pacientes.map((paciente, index) => (
              <tr key={paciente.id}>
                <td>{paciente.name}</td>
                <td>{paciente.birth date}</td>
                <td>{paciente.cpf}</td>
                <td>{paciente.gender}</td>
                <td>{paciente.address}</td>
                <td>{paciente.status}</td>
                <td>
                  <Button className="button muted-button" onClick={() => removePaciente(index)}>
                    <i style={{ color: "red" }} className="fa-solid fa-trash fa-xl"></i>
                  </Button>
                  <Button className="button muted-button">
                    <i style={{ color: "orange" }} className="fa-solid fa-pen-to-square fa-xl"></i>
                  </Button>
                  {/* {condition === true ? <Cadastrar /> : <ListarPacientes />} */}
                </td>
              </tr>
            ))
          ) : (
            <tr>
              <td colSpan={3}>Sem pacientes</td>
            </tr>
          )}
        </tbody>
      </Table>
    </div>
  )
}
export default ListPatients

结果

注意:我正在使用 localStorage 来存储数据。

我如何使用搜索输入来做到这一点?请帮忙

很简单。您将需要定义将保持 searchInput

的状态
const [searchInput, setSearchInput] = useState()

然后你应该创建一个函数来过滤你的病人

const getFilteredPatients = () => {
  if (!searchInput) return patients
  return patients.filter(patient => patient.name.toLowerCase() === searchInput.toLowerCase())
}

在适当的地方调用即可。

整体应该是这样的

const ListPatients = props => {
  const { patients, setPatients } = props

  const [searchInput, setSearchInput] = useState()

  const removePatient = patientId => {
    const newPatients = patients.filter(patient => patient.id !== patientId)
    setPatients(newPatients)
  }

  const getFilteredPatients = () => {
    if (!searchInput) return patients
    return patients.filter(
      patient => patient.name.toLowerCase() === searchInput.toLowerCase()
    )
  }

  const filteredPatients = getFilteredPatients()

  return (
    <div>
      <h1>List</h1>
      <Table style={{ border: '1' }}>
        <thead>
          <tr style={{ padding: '0 1rem' }}>
            <th>Name</th>
            <th>Birth date</th>
            <th>CPF</th>
            <th>Gender</th>
            <th>Addres</th>
            <th>Status</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {patients.length === 0 && (
            <tr>
              <td colSpan={3}>Sem pacientes</td>
            </tr>
          )}

          {filteredPatients.map(patient => (
            <tr key={patient.id}>
              <td>{patient.name}</td>
              <td>{patient.birth_date}</td>
              <td>{patient.cpf}</td>
              <td>{patient.gender}</td>
              <td>{patient.address}</td>
              <td>{patient.status}</td>
              <td>
                <Button
                  className="button muted-button"
                  onClick={() => removePatient(patient.id)}
                >
                  <i
                    style={{ color: 'red' }}
                    className="fa-solid fa-trash fa-xl"
                  />
                </Button>
                <Button className="button muted-button">
                  <i
                    style={{ color: 'orange' }}
                    className="fa-solid fa-pen-to-square fa-xl"
                  />
                </Button>
              </td>
            </tr>
          ))}
        </tbody>
      </Table>
    </div>
  )
}

export default ListPatients

我在你的代码中修改了 3 个主要部分

首先,你需要导入这些

import React, { useState, useEffect } from 'react'

之后我们开始实施

//initialise search value
const [searchValue, setSearchValue] = useState("")

//whenever search value gets updated, we will update patience list
  useEffect(() => {
    const newPacientes = pacientes.filter(value => value.name.toLowerCase().includes(searchValue.toLowerCase()))
    setPacientes(newPacientes)
  }, [searchValue])

最后,我们需要有搜索输入字段

<input type="text" onChange={(e) => setSearchValue(e.target.value)} value={searchValue} placeholder="Search by name"/>

import React, { useState, useEffect } from 'react'

const ListPatients = ({ pacientes, setPacientes }) => {
  //initialise search value
  const [searchValue, setSearchValue] = useState("")
  
  //whenever search value gets updated, we will update patience list
  useEffect(() => {
    const newPacientes = pacientes.filter(value => value.name.toLowerCase().includes(searchValue.toLowerCase()))
    setPacientes(newPacientes)
  }, [searchValue])
  
  const removePaciente = (idToDelete) => {
    const newTasks = [...pacientes];
    newTasks.splice(idToDelete, 1);
    setPacientes(newTasks);
  };
  return (
    <div style={{ display:"flex", alignItems:"center", flexDirection:'column'}}>
      <h1>List</h1>
      <input type="text" onChange={(e) => setSearchValue(e.target.value)} value={searchValue} placeholder="Search by name"/>
      <Table style={{ border:'1'}}>
        <thead>
          <tr style={{padding:'0 1rem'}}>
            <th>Name</th>
            <th>Birth date</th>
            <th>CPF</th>
            <th>Gender</th>
            <th>Addres</th>
            <th>Status</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {pacientes.length > 0 ? (
            pacientes.map((paciente, index) => (
              <tr key={paciente.id}>
                <td>{paciente.name}</td>
                <td>{paciente.birth date}</td>
                <td>{paciente.cpf}</td>
                <td>{paciente.gender}</td>
                <td>{paciente.address}</td>
                <td>{paciente.status}</td>
                <td>
                  <Button className="button muted-button" onClick={() => removePaciente(index)}>
                    <i style={{ color: "red" }} className="fa-solid fa-trash fa-xl"></i>
                  </Button>
                  <Button className="button muted-button">
                    <i style={{ color: "orange" }} className="fa-solid fa-pen-to-square fa-xl"></i>
                  </Button>
                  {/* {condition === true ? <Cadastrar /> : <ListarPacientes />} */}
                </td>
              </tr>
            ))
          ) : (
            <tr>
              <td colSpan={3}>Sem pacientes</td>
            </tr>
          )}
        </tbody>
      </Table>
    </div>
  )
}
export default ListPatients