我正在尝试在ReactJS中实现搜索功能。我不知道该怎么做。下面我给出了我尝试过的代码。
我需要在serach之后在表中显示结果。
render() {
return (
<div>
<input onChange={this.handleSearchChange} placeholder="Search"/>
</div>
)
}
//下面是我的功能
handleSearchChange = e => {
const { value } = e.target;
var self = this
axios.post("http://localhost:4000/get", { name: value })
.then(function(res){
console.log("detail",res.data)
})
.catch(function(err){
console.log('Error',err)
})
};
//下面是我的api响应
[
{color: "green",name: "test",age: "22"},
{color: "red",name: "test2",age: "23"}
]
一旦有了数据,就需要将其添加到状态,以便在状态更改时可以迭代数据并重新生成视图。我在这个例子中使用了React钩子。希望能帮上点忙。
null
table {
background-color: white;
border-collapse: collapse;
}
tr:nth-child(even) {
background-color: #efefef;
}
td {
padding: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone@7/babel.min.js"></script>
<script type="text/babel">
// Grab the hooks you need
const { useState, useEffect } = React;
// The main function that will loop over the data
// and create the rows for the table
function createRows(data) {
// Iterate over the data and for each object
// return a new HTML row
return data.map((row, i) => {
const { color, name, age } = row;
return (
<tr key={i}>
<td>{color}</td>
<td>{name}</td>
<td>{age}</td>
</tr>
)
});
}
// Mock API call which returns data after a 2 second delay
function fakeAPICall() {
return new Promise((res, rej) => {
setTimeout(() => {
res('[{"color": "green","name": "test","age": "22"},{"color": "red","name": "test2","age": "23"}]');
}, 2000);
});
}
function Example () {
// Set up the state in the componenent
const [data, setData] = useState([]);
// When the component renders load in the data
// and set that as your state.
useEffect(() => {
async function getData() {
const response = await fakeAPICall();
const data = JSON.parse(response);
setData(data);
}
getData();
}, []);
// If there's no data in state display nothing...
if (!data.length) return <div>No data</div>
// ...otherwise pass the data into the createRows function
// and return them the row data
return (
<table>
<thead>
<th>Color</th>
<th>Name</th>
<th>Age</th>
</thead>
<tbody>
{createRows(data)}
</tbody>
</table>
)
};
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);
</script>
<div id="react"></div>