我正在使用React自动完成组件,如官方文档中的国家范例。
我的目标是以粗体显示国家代码,就像我在renderOption中已经做的那样,简单地将option.code值用HTML标记括起来。
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.code} ${option.label}`} // DISPLAY THE CODE
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=""
/>
{option.label} (<b>{option.code}</b>) +{option.phone}
</Box>
)}
renderInput={(params) => (
<TextField
{...params}
label="Choose a country"
inputProps={{
...params.inputProps,
autoComplete: 'new-password', // disable autocomplete and autofill
}}
/>
)}
/>
);
}
我无法找到在option.code属性中引用renderInput的方法,因此我无法找到如何在renderInput中以粗体显示国家代码,因为粗体只有在选择选项时才可见,而在选择该选项时则不能显示。
有什么解决办法吗?
发布于 2022-07-06 10:13:29
这方面的主要问题是MUI由HTML组成。
它的值只能是string类型,它禁止任何直接的值样式,但是您可以使用如下所示的startAdornment:
...
renderInput={(params) => (
<TextField
{...params}
label="Choose a country"
inputProps={{
...params.inputProps,
autoComplete: "new-password" // disable autocomplete and autofill
}}
InputProps={{
...params.InputProps,
startAdornment: <strong>{params.inputProps.value.split(" ")[0]}</strong>
}}
/>
)}
...您的下一个挑战将是从输入值中删除附加的国家代码,甚至更好的是,移至受控值方法。
https://stackoverflow.com/questions/72172519
复制相似问题