如何为反应表添加基本搜索功能



我在react app中创建了一个表,它目前只有行和列。我想添加一个基本的搜索功能,用户可以在其中键入名称并获得与该名称匹配的行。我在网上看过一些示例,但是没有一个涉及如何为我创建的表类型添加搜索功能。有什么技巧或知识如何做到这一点给我的代码。

import React from "react";
import './App.css';
class App extends React.Component {

// Constructor 
constructor(props) {
super(props);

this.state = {
items: [],
DataisLoaded: false
};
}

// ComponentDidMount is used to
// execute the code 
componentDidMount() {
fetch(
"http://ec2-34-213-215-13.us-west-2.compute.amazonaws.com:3001/getPatients")
.then((res) => res.json())
.then((json) => {
this.setState({
items: json,
DataisLoaded: true
});
})
}
render() {
const { DataisLoaded, items } = this.state;
if (!DataisLoaded) return <div>
<h1> Please wait some time.... </h1> </div> ;

return (
<div className = "App">
<h1> Welcome to the Master Patient Index </h1>  {
<table class="center">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>DOB</th>
<th>Gender</th>
<th>SSN</th>
<th>Race</th>
<th>Ethnicity</th>
<th>Marital</th>
<th>Drivers License</th>
<th>Passport</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>County</th>
<th>Zip</th>
</tr>
{items.map((items, key) => {
return (
<tr key={key}>
<td>{items.FIRST}</td>
<td>{items.LAST}</td>
<td>{items.BIRTHDATE}</td>
<td>{items.GENDER}</td>
<td>{items.SSN}</td>
<td>{items.RACE}</td>
<td>{items.ETHNICITY}</td>
<td>{items.MARITAL}</td>
<td>{items.DRIVERS}</td>
<td>{items.PASSPORT}</td>
<td>{items.ADDRESS}</td>
<td>{items.CITY}</td>
<td>{items.STATE}</td>
<td>{items.COUNTY}</td>
<td>{items.ZIP}</td>
</tr>
)
})}
</table>
}
</div>
);
}
}

export default App;

我将通过为您的状态添加一个名为searchTerm的新属性来做到这一点。

constructor(props) {
super(props);
this.state = {
items: [],
searchTerm: ''
};
this.handleChange = this.handleChange.bind(this);
}

handleChange(event) {
this.setState({
[event.target.name]: event.target.value 
})
}

然后添加一个输入字段来更新searchTerm

<input placeholder="search here..." value={searchTerm} name="searchTerm" onChange={this.handleChange}  />

然后用.filter数组法按搜索项

进行过滤
{items
.filter(items => items.FIRST.toLowerCase().includes(searchTerm.toLowerCase())) 
.map((items, key) => {
return (
<tr key={key}>
<td>{items.FIRST}</td>
</tr>
)
})}

完整代码:(简化版代码)

https://codesandbox.io/s/cool-bird-i2nj5o?file=/src/App.js: 844 - 1183

最新更新