在 reactjs 中实现搜索功能
implementation of search functionality in reactjs
我正在尝试在 reactjs 中实现搜索功能。我不知道该怎么做。下面我给出了我试过的代码。
我需要在 serach 之后在 table 中显示结果。
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 hooks。希望对大家有所帮助。
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>
下面是我使用 class 组件的方法:
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 type="text/babel">
// 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);
});
}
class Example extends React.Component {
// Set up the state in the componenent
constructor() {
super();
this.state = { data: [] };
}
// When the component renders load in the data
// and set that as your state.
componentDidMount() {
fakeAPICall().then(response => {
return JSON.parse(response);
}).then(data => {
this.setState({ data });
});
}
// ...otherwise pass the data into the createRows function
// and return them the row data
render() {
if (!this.state.data.length) return <div/>
return (
<table>
<thead>
<th>Color</th>
<th>Name</th>
<th>Age</th>
</thead>
<tbody>
{createRows(this.state.data)}
</tbody>
</table>
)
}
}
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);
</script>
<div id="react"></div>
如果我正确理解你的问题,你正在尝试更新你的 table 渲染。正如你提到的,我假设你的 API 在通话中工作正常。
在React中,有一个叫做“状态”的特性,可以保存一个可变的状态。很酷的一点还在于,当您更改该状态时,您的组件会重新呈现。一点解释或 ReactJS 声明:
// intialization of a variable "varX" of type integer with value 1
// setVarX(int) is used to change the variable state
const [varX, setVarX] = React.useState(1);
// changing the state
setVarX(3);
因此,对于您的问题,我们需要两件事:保存 API 响应的状态,只要 API 有新数据我们就会更新,以及 table 显示你的数据。
州
在您正在呈现的函数中(我假设它是名称 TableView),让我们添加此状态并在 API 成功时在处理程序中更新它
function TableView(){
// table data, initialized to empty array
const [tableData, setTableData] = React.useState([]);
// handle updated with set state
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)
setTableData(res.data) // update the table data!
})
.catch(function(err){
console.log('Error',err)
})
};
return (...) // render function in the next section
}
渲染
该函数将使用 react 的 map 功能:
render() {
return (
<div>
<input onChange={this.handleSearchChange} placeholder="Search"/>
<table style="width:100%">
<tr>
<th>Color</th>
<th>Name</th>
<th>Age</th>
</tr>
</table>
{
tableData.map((entry, index) =>
<tr index={index}>
<td>{entry.color}</td>
<td>{entry.name}</td>
<td>{entry.age}</td>
</tr>
)
}
</div>
)
}
PS:我不是最擅长 JSX 的,请随意编辑和增强渲染部分
我正在尝试在 reactjs 中实现搜索功能。我不知道该怎么做。下面我给出了我试过的代码。
我需要在 serach 之后在 table 中显示结果。
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 hooks。希望对大家有所帮助。
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>
下面是我使用 class 组件的方法:
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 type="text/babel">
// 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);
});
}
class Example extends React.Component {
// Set up the state in the componenent
constructor() {
super();
this.state = { data: [] };
}
// When the component renders load in the data
// and set that as your state.
componentDidMount() {
fakeAPICall().then(response => {
return JSON.parse(response);
}).then(data => {
this.setState({ data });
});
}
// ...otherwise pass the data into the createRows function
// and return them the row data
render() {
if (!this.state.data.length) return <div/>
return (
<table>
<thead>
<th>Color</th>
<th>Name</th>
<th>Age</th>
</thead>
<tbody>
{createRows(this.state.data)}
</tbody>
</table>
)
}
}
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);
</script>
<div id="react"></div>
如果我正确理解你的问题,你正在尝试更新你的 table 渲染。正如你提到的,我假设你的 API 在通话中工作正常。
在React中,有一个叫做“状态”的特性,可以保存一个可变的状态。很酷的一点还在于,当您更改该状态时,您的组件会重新呈现。一点解释或 ReactJS 声明:
// intialization of a variable "varX" of type integer with value 1
// setVarX(int) is used to change the variable state
const [varX, setVarX] = React.useState(1);
// changing the state
setVarX(3);
因此,对于您的问题,我们需要两件事:保存 API 响应的状态,只要 API 有新数据我们就会更新,以及 table 显示你的数据。
州
在您正在呈现的函数中(我假设它是名称 TableView),让我们添加此状态并在 API 成功时在处理程序中更新它
function TableView(){
// table data, initialized to empty array
const [tableData, setTableData] = React.useState([]);
// handle updated with set state
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)
setTableData(res.data) // update the table data!
})
.catch(function(err){
console.log('Error',err)
})
};
return (...) // render function in the next section
}
渲染
该函数将使用 react 的 map 功能:
render() {
return (
<div>
<input onChange={this.handleSearchChange} placeholder="Search"/>
<table style="width:100%">
<tr>
<th>Color</th>
<th>Name</th>
<th>Age</th>
</tr>
</table>
{
tableData.map((entry, index) =>
<tr index={index}>
<td>{entry.color}</td>
<td>{entry.name}</td>
<td>{entry.age}</td>
</tr>
)
}
</div>
)
}
PS:我不是最擅长 JSX 的,请随意编辑和增强渲染部分