React/TypeScript中如何存储MUI Autocomplete选中值并发送至API?
实现方案
1. 先定义TypeScript类型(保障类型安全)
首先给角色数据定义明确的类型,避免后续类型错误:
interface Role { id: number; // 请根据你的实际数据结构调整字段 title: string; // 其他需要的属性... }
2. 用React状态管理选中值
通过useState钩子创建状态,存储用户选中的所有选项:
import { useState } from 'react'; const [selectedRoles, setSelectedRoles] = useState<Role[]>([]);
3. 配置Autocomplete组件
给组件绑定状态和更新逻辑,核心是添加value和onChange属性:
<Autocomplete multiple id="tags-roles" options={roles} getOptionLabel={(option) => option.title} // 绑定选中状态 value={selectedRoles} // 选中/取消选项时更新状态 onChange={(_event, newValue) => { setSelectedRoles(newValue); }} renderInput={(params) => ( <TextField {...params} variant="standard" label="Choose Roles" placeholder="Roles" /> )} />
4. 实现API提交逻辑
编写提交函数,将选中的角色数据发送到后端,这里用原生fetch示例(你也可以用axios等工具):
const handleSubmit = async () => { try { // 根据后端要求处理数据,比如只发送id数组 const submitData = selectedRoles.map(role => role.id); // 若后端需要完整对象,直接传selectedRoles即可 const response = await fetch('你的API接口地址', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ roles: submitData }), }); if (!response.ok) { throw new Error('提交失败'); } const result = await response.json(); console.log('提交成功:', result); // 提交完成后可添加重置状态、提示用户等逻辑 setSelectedRoles([]); } catch (error) { console.error('提交出错:', error); // 错误处理,比如提示用户 } };
添加触发提交的按钮:
<button style={{ marginTop: '16px' }} onClick={handleSubmit}> 提交选中角色 </button>
完整代码示例
import React, { useState } from 'react'; import Autocomplete from '@mui/material/Autocomplete'; import TextField from '@mui/material/TextField'; interface Role { id: number; title: string; } const RoleSelector = () => { // 模拟角色数据,实际可从API获取或通过props传入 const roles: Role[] = [ { id: 1, title: '管理员' }, { id: 2, title: '编辑' }, { id: 3, title: '访客' }, ]; const [selectedRoles, setSelectedRoles] = useState<Role[]>([]); const handleSubmit = async () => { try { const submitData = selectedRoles.map(role => role.id); const response = await fetch('https://your-api-url.com/submit-roles', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ selectedRoles: submitData }), }); if (!response.ok) throw new Error('请求失败'); const data = await response.json(); console.log('提交成功:', data); setSelectedRoles([]); } catch (err) { console.error('提交出错:', err); } }; return ( <div> <Autocomplete multiple id="tags-roles" options={roles} getOptionLabel={(option) => option.title} value={selectedRoles} onChange={(_event, newValue) => setSelectedRoles(newValue)} renderInput={(params) => ( <TextField {...params} variant="standard" label="Choose Roles" placeholder="Roles" /> )} /> <button style={{ marginTop: 16 }} onClick={handleSubmit}> 提交选中角色 </button> </div> ); }; export default RoleSelector;
关键说明
value:将组件的选中值与React状态绑定,确保视图和状态同步onChange:用户修改选中项时触发,newValue就是当前所有选中的选项数组- TypeScript类型:提前定义
Role接口,能获得编辑器的类型提示,避免低级错误 - API提交:根据后端接口要求调整提交数据的格式,比如只传id或完整对象
内容的提问来源于stack exchange,提问作者Mango
相关产品推荐
相关产品推荐

