[英]React MUI Autocomplete - Customizing renderInput content
I'm using the React MUI Autocomplete component like in the countries example from the official doc.我正在使用 React MUI Autocomplete 组件,就像官方文档中的 国家示例一样。
My goal is to display in bold the country code , as I already did in the renderOption by simply enclosing the option.code value with HTML tags.我的目标是以粗体显示国家代码,就像我在 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
}}
/>
)}
/>
);
}
I cannot find a way to reference the option.code inside the renderInput property, so I cannot figure out how to display the country code in bold also in the renderInput, since the bold is only visible when choosing an option, but not when that option is selected.我找不到在 renderInput 属性中引用 option.code 的方法,因此我无法弄清楚如何在 renderInput中以粗体显示国家代码,因为粗体仅在选择选项时可见,但在该选项时不可见被选中。
Is there a solution for this?有解决方案吗?
The main problem with this is that MUI Textfields consist of HTML <input/>
tags.这样做的主要问题是 MUI 文本字段由 HTML
<input/>
标签组成。
Its value can only be of type string which prohibits any direct value styling but you can make use of an startAdornment
like so:它的值只能是禁止任何直接值样式的字符串类型,但您可以像这样使用
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>
}}
/>
)}
...
Your next challenge would be to remove the additional country code from the input-value or even better, move to a controlled value approach.您的下一个挑战是从输入值中删除额外的国家/地区代码,或者更好的是,转向受控值方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.