您正在使用受控输入渲染 Autocomplete
组件。在这种情况下,您需要在控制 Autocomplete
选定值的 useState
中设置默认值。您可以参阅此处的文档:Autocomplete API 文档。文档中这样写道:
defaultValue: 默认值。在组件处于非受控状态时使用。
假设选项 “All” 总是位于列表顶部,您可以按如下方式初始化 selectedNamesState
:
const [selectedNamesState, setSelectedNamesState] = useState([
{
label: "All",
value: "0",
},
]);
您的 options
数组是对象数组。如果您愿意将其转换为字符串数组,解决方案会更加简单:
import { Autocomplete, Chip, TextField } from "@mui/material";
import { useState } from "react";
const someKey = "someKey";
const stateNPAValue = {
[someKey]: ["All", "959", "203", "860", "475"],
};
function App() {
const [selectedNamesState, setSelectedNamesState] = useState(["All"]);
const transformedNpaData = stateNPAValue[someKey];
return (
<div className="App">
<Autocomplete
multiple
id="fixed-tags-demo"
name="Npa"
value={selectedNamesState}
onChange={(event, newValue) => {
setSelectedNamesState(newValue);
}}
options={transformedNpaData}
getOptionLabel={(option) => {
return option.replace(/[[\]']+/g, "");
}}
// defaultValue={[transformedNpaData[0].label]}
renderTags={(tagValue, getTagProps) =>
tagValue.map((option, index) => (
<Chip
key={option}
label={option.replace(/[[\]']+/g, "")}
{...getTagProps({ index })}
/>
))
}
style={{ width: 500 }}
renderInput={(params) => <TextField {...params} label="test" />}
/>
</div>
);
}
export default App;