You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在表单提交时获取React Material自定义Autocomplete组件的ID

如何让MUI Autocomplete组件在表单提交时返回选项的ID而非标签?

你可以通过两种方式实现需求,以下是具体修改方案:

方法一:利用Autocomplete的getOptionValue属性(简洁版)

MUI的Autocomplete组件自带getOptionValue属性,用于定义每个选项对应的表单提交值,默认会复用getOptionLabel的返回结果。我们只需要将该属性设置为返回选项的id即可:

import { Autocomplete, TextField } from "@mui/material"

const animalOptions = [
    { id: 1, label: 'Bear' },
    { id: 2, label: 'Wolf' },
    { id: 4, label: 'Cat' },
    { id: 5, label: 'Dog' },
    { id: 6, label: 'Bird' },
    { id: 7, label: 'Elephant' },
];

export const AnimalSelect = ({ id }) => {
    return (
        <Autocomplete
            id={id}
            options={animalOptions}
            renderInput={params => <TextField {...params} />}
            getOptionLabel={option => option.label}
            // 指定选项对应的表单值为id的字符串形式
            getOptionValue={option => option.id.toString()}
        />
    );
}

修改后,表单提交时e.target.elements.animals.value会直接返回选中动物的id字符串。

方法二:添加隐藏input同步选中值(灵活版)

如果需要更直观地控制表单字段,或者要对选中值做额外处理,可以在组件内部添加一个隐藏的input元素,同步选中选项的id:

import { Autocomplete, TextField } from "@mui/material"
import { useState } from "react";

const animalOptions = [
    { id: 1, label: 'Bear' },
    { id: 2, label: 'Wolf' },
    { id: 4, label: 'Cat' },
    { id: 5, label: 'Dog' },
    { id: 6, label: 'Bird' },
    { id: 7, label: 'Elephant' },
];

export const AnimalSelect = ({ id }) => {
    const [selectedId, setSelectedId] = useState('');

    return (
        <>
            <Autocomplete
                id={`${id}-autocomplete`}
                options={animalOptions}
                renderInput={params => <TextField {...params} />}
                getOptionLabel={option => option.label}
                onChange={(event, value) => {
                    // 选中选项时更新id,未选中则清空
                    setSelectedId(value ? value.id.toString() : '');
                }}
            />
            {/* 隐藏input,与原组件id一致,表单提交时会携带该值 */}
            <input
                type="hidden"
                id={id}
                name={id}
                value={selectedId}
            />
        </>
    );
}

这种方式下,父组件的handleSubmit逻辑无需修改,提交时依然通过e.target.elements.animals.value获取选中的id。


内容的提问来源于stack exchange,提问作者kailoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 20:34:55