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

React MUI Autocomplete组件自定义:通过renderInput实现选中项旁显示国旗

Absolutely! You can absolutely add the flag next to the selected country name in the TextField—here's how to do it cleanly with MUI's Autocomplete and TextField components:

Modified CountrySelect Component

import * as React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

export default function CountrySelect() {
  return (
    <Autocomplete
      id="country-select-demo"
      sx={{ width: 300 }}
      options={countries}
      autoHighlight
      getOptionLabel={(option) => option.label}
      renderOption={(props, option) => (
        <Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
          <img
            loading="lazy"
            width="20"
            src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
            srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
            alt={`Flag of ${option.label}`}
          />
          {option.label} ({option.code}) +{option.phone}
        </Box>
      )}
      renderInput={(params) => {
        // Grab the currently selected country object
        const selectedCountry = params.value;
        
        // Build the flag adornment only when a country is selected
        const flagAdornment = selectedCountry ? (
          <Box sx={{ mr: 1, display: 'flex', alignItems: 'center' }}>
            <img
              loading="lazy"
              width="20"
              src={`https://flagcdn.com/w20/${selectedCountry.code.toLowerCase()}.png`}
              srcSet={`https://flagcdn.com/w40/${selectedCountry.code.toLowerCase()}.png 2x`}
              alt={`Flag of ${selectedCountry.label}`}
            />
          </Box>
        ) : null;

        return (
          <TextField
            {...params}
            label="Choose a country"
            InputProps={{
              ...params.InputProps,
              startAdornment: (
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  {flagAdornment}
                  {params.InputProps.startAdornment}
                </Box>
              ),
            }}
            inputProps={{
              ...params.inputProps,
              autoComplete: 'new-password', // disable autocomplete and autofill
            }}
          />
        );
      }}
    />
  );
}

// Truncated country data (add your full list here)
const countries = [
  { code: 'AD', label: 'Andorra', phone: '376' },
  { code: 'AE', label: 'United Arab Emirates', phone: '971' },
];

Key Changes Explained

  1. Access Selected Value: We pull params.value in the renderInput function—this gives us the full country object when a selection is made.
  2. Conditional Flag Adornment: We only render the flag when a valid country is selected. This keeps the input clean when the user is typing or hasn't chosen an option yet.
  3. Merge Input Props: We combine the default params.InputProps with our custom startAdornment to avoid overwriting any built-in behavior (like the clear button, if you enable it later). The flag is placed before the input text with a small margin to keep spacing clean.
  4. Consistent Flag Logic: We reuse the same flag URL pattern from the dropdown options to ensure visual consistency between the list and the selected input.

This approach keeps your existing dropdown behavior intact while adding the flag to the selected state exactly as you wanted.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:27:33