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

Material-UI Autocomplete多选择场景:如何为TextField的startAdornment手动添加选中值

Solution for Customizing Material-UI Autocomplete's TextField Start Adornment with Complex Selected Options

Got it, let's break down how to manually add your selected complex objects to the startAdornment of the TextField in a multi-select Material-UI Autocomplete. The key is to take full control of the selected values and render them exactly how you want, without relying on modifying the params object directly.

Step-by-Step Approach

  1. Manage Selected State: First, hold your selected options in a state variable so you can easily access and manipulate them.
  2. Disable Default Tags: Turn off Autocomplete's default selected tag rendering (since we're moving this to the startAdornment).
  3. Build Custom Start Adornment: Map your complex selected objects into the UI elements you want (like Chips with custom content) and combine them with any existing startAdornment from the params.
  4. Add Delete Functionality: Optional but useful—let users remove individual selections directly from the adornment.

Full Code Example

import React, { useState } from 'react';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import Chip from '@mui/material/Chip';
import Box from '@mui/material/Box';

// Your complex city options
const cities = [
  { id: 1, name: 'New York', country: 'USA', population: 8468000 },
  { id: 2, name: 'London', country: 'UK', population: 9304016 },
  { id: 3, name: 'Paris', country: 'France', population: 2161000 },
];

export default function CustomAdornmentAutocomplete() {
  const [selectedCities, setSelectedCities] = useState([]);

  return (
    <Autocomplete
      multiple
      options={cities}
      value={selectedCities}
      onChange={(event, newValue) => setSelectedCities(newValue)}
      getOptionLabel={(option) => option.name}
      renderTags={() => null} // Disable default tag rendering
      renderInput={(params) => {
        // Build your custom start adornment from selected values
        const customStartAdornment = (
          <Box sx={{ display: 'flex', gap: 0.5, mr: 1, flexWrap: 'wrap' }}>
            {selectedCities.map((city) => (
              <Chip
                key={city.id}
                label={`${city.name}, ${city.country}`} // Use complex object fields
                size="small"
                onDelete={() => {
                  // Handle removing a single selected option
                  setSelectedCities(selectedCities.filter(c => c.id !== city.id));
                }}
              />
            ))}
          </Box>
        );

        return (
          <TextField
            {...params}
            variant="outlined"
            label="Cities"
            placeholder="Enter cities"
            autoComplete="off"
            InputProps={{
              ...params.InputProps,
              // Merge custom adornment with existing startAdornment
              startAdornment: (
                <React.Fragment>
                  {customStartAdornment}
                  {params.InputProps.startAdornment}
                </React.Fragment>
              ),
              endAdornment: (
                <React.Fragment>
                  {params.InputProps.endAdornment}
                </React.Fragment>
              )
            }}
          />
        );
      }}
    />
  );
}

Key Details

  • State Management: By using useState for selectedCities, you have full control over the selected values, making it easy to map them into UI elements regardless of how complex the object structure is.
  • Custom Rendering: The customStartAdornment lets you display any part of your selected objects (like city name + country in the example) instead of being limited to the default tag format.
  • Preserve Default Functionality: We spread params.InputProps and merge our custom adornment with the original startAdornment, so you don't lose any built-in TextField features.
  • Delete Handling: The onDelete handler on each Chip lets users remove selections directly from the adornment, which updates the state and syncs with the Autocomplete component automatically.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 06:02:39