将选择的选项发送到后端



我有一个选择菜单(有三个选项)和一个搜索栏。我所要做的就是保存选中的选项和搜索项,并将它们发送到后端。下面是我的代码:

import React, { useState, useEffect } from 'react'
const Table = () => {
const navigate = useNavigate()
const [users, setUsers] = useState([]);
const [currentUsers, setCurrentUsers] = useState([]);
const [search, setSearch] = useState('');
const [column, setColumn] = useState(''); //for saving the selected option
useEffect(async () => {
try {
const response = await getUsers(search);
setUsers(response.data.users);
} catch (error) { }
}, [search]);
return (
<input type='text' placeholder='search..' onChange={(e) => setSearch(e.target.value)} value={search} />
<select aria-label=".form-select-sm example">
<option selected value="1">all</option>
<option value="2">name</option>
<option value="3">phone</option>
</select>
<table className='w-full border-separate rounded-md'>
<thead>
<tr className='bg-text-secondary text-white shadow-sm text-center'>
<th className='p-2'>name</th>
<th className='p-2'>phone</th>
</tr>
</thead>
<tbody>
{currentUsers.map((item, index) =>
<tr key={item.id} className={index % 2 === 0 ? 'bg-white shadow-sm text-center' : 'bg-text bg-opacity-5 shadow-sm text-center'}>
<td className='text-text text-sm p-2'>{item.name}</td>
<td className='text-text text-sm p-2'>{item.phone}</td>
</tr>
)}
</tbody>
</table>
)
}

我已经成功地在后端接收了搜索词,但我不知道如何将其应用于所选选项。我尝试在每个选项上添加onClick()onChange()并保存状态,但我没有成功。我该怎么做呢?

你的onChange应该在select标签上。以下是我所做的。

import React, { useState, useEffect } from "react";
const Table = () => {
const navigate = useNavigate()
const [users, setUsers] = useState([]);
const [currentUsers, setCurrentUsers] = useState([]);
const [search, setSearch] = useState("");
const [column, setColumn] = useState(""); //for saving the selected option
useEffect(async () => {
try {
const response = await getUsers(search);
setUsers(response.data.users);
} catch (error) { }
}, [search]);
return (
<>
<input
type="text"
placeholder="search.."
onChange={(e) => setSearch(e.target.value)}
value={search}
/>
// added here
<select
aria-label=".form-select-sm example"
onChange={(e) => {
setColumn(e.target.value);
console.log(e.target.value);
}}
>
<option selected value="1">
all
</option>
<option value="2">name</option>
<option value="3">phone</option>
</select>
<table className="w-full border-separate rounded-md">
<thead>
<tr className="bg-text-secondary text-white shadow-sm text-center">
<th className="p-2">name</th>
<th className="p-2">phone</th>
</tr>
</thead>
<tbody>
{currentUsers.map((item, index) => (
<tr
key={item.id}
className={
index % 2 === 0
? "bg-white shadow-sm text-center"
: "bg-text bg-opacity-5 shadow-sm text-center"
}
>
<td className="text-text text-sm p-2">{item.name}</td>
<td className="text-text text-sm p-2">{item.phone}</td>
</tr>
))}
</tbody>
</table>
</>
);
};

最新更新