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
- Access Selected Value: We pull
params.valuein therenderInputfunction—this gives us the full country object when a selection is made. - 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.
- Merge Input Props: We combine the default
params.InputPropswith our customstartAdornmentto 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. - 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
相关产品推荐
相关产品推荐

