[英]How to make MUI's Autocomplete display the label from the matching value in props.options?
我有一个多语言网站,其中有某些自动完成功能,其选项数组需要翻译其项目标签,这很容易完成。
但是,更新存储在其他地方的当前选择的值会更难。 由于 Autocomplete 使用 value 属性中的标签,而不是在选项中使用相同 ID 的项目,因此最终结果如下:
const vehicles = [
{ id: 1, label: "Car" },
{ id: 2, label: "Bus" }
];
const currentVehicleValue = {
id: 2,
label: "Ônibus"
};
export default function ComboBox() {
return (
<Autocomplete
disablePortal
id="combo-box-demo"
options={vehicles}
value={currentVehicleValue}
renderInput={(params) => <TextField {...params} label="Vehicle" />}
/>
);
}
有没有办法告诉自动完成使用选项道具中的标签而不是值中的标签
编辑:我的意思是在我不输入任何内容时显示选项中的标签。 如,语言改变了,选项被翻译了,但 currentValue 没有,所以只要我不输入任何内容,让自动完成功能使用选项中匹配项目的标签会很好。
您可以通过调整接收到的props
来更改<TextField/>
的呈现方式。
在下面的示例中,我通过其id
找到currentVehicle
并将inputProps.value
更改为车辆标签。
此外,为确保 MUI 在选项中正确找到 currentValue,您将需要使用isOptionEqualToValue
来比较选项 id 而不是严格相等
const vehicles = [
{ id: 1, label: "Car" },
{ id: 2, label: "Bus" }
];
const currentVehicleValue = {
id: 2,
label: "Ônibus"
};
function compareValueToOption(option, value) {
return option.id === value.id;
}
function ComboBox() {
return (
<Autocomplete
disablePortal
id="combo-box-demo"
options={vehicles}
value={currentVehicleValue}
renderInput={ComboBoxInput}
isOptionEqualToValue={compareValueToOption}
/>
);
}
function ComboBoxInput(props) {
const currentVehicle = vehicles.find(
(vehicle) => vehicle.id === currentVehicleValue.id
);
props.inputProps.value = currentVehicle.label;
return <TextField {...props} label="Vehicle" />;
}
这是一个工作演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.