如何在React中自定义Mui的自动完成?

问题描述 投票:0回答:1
reactjs mui-x
1个回答
0
投票

我找到了解决方案,它根据所选国家/地区自定义 renderInputs。我提供我的解决方案代码。

export default function CountrySelect({selectedCountry, onChange}) {
    const renderInput = (params: any) => {
        return (
          <TextField
                {...params}
                placeholder="Select a country"
                InputProps={{
                    ...params.InputProps,
                    startAdornment: (selectedCountry != null && selectedCountry != undefined && selectedCountry != '') ? (
                        <img 
                            src={`https://flagcdn.com/w20/${selectedCountry?.code?.toLowerCase()}.png`}
                            alt={selectedCountry?.label} 
                            style={{
                                margin: 0,
                                paddingLeft: '16px'
                            }}
                        />
                    ) : null
                }}
          />
        )
    };
    
    return (
        <Autocomplete
            value={selectedCountry}
            onChange={onChange}
            id="country-select"
            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"
                        srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
                        src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
                        alt=""
                    />
                    {option.label} ({option.code}) +{option.phone}
                </Box>
            )}
            renderInput={renderInput}
        />
    );
}

谢谢大家。

© www.soinside.com 2019 - 2024. All rights reserved.