我有一个 Material UI 选择框,当它们最初是选择选项时,它没有应用选择。我创建了一个代码沙箱,您可以在其中看到最初指定的前两个选项未在选择字段中选择,如果再次选择其中任何一个,则会产生重复的选择。但是,如果变量最初初始化为空数组,
则一切正常。
有没有办法在不将类型更改为字符串数组的情况下解决这个问题?selectedOptions
[]
availableOptions
import React, { Component } from "react";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import ListItemText from "@material-ui/core/ListItemText";
import Select from "@material-ui/core/Select";
export default class renderFixedField extends Component {
state = {
availableOptions: [],
selectedOptions: []
};
componentWillMount = () => {
const availableOptions = [
{ friendly: "code1", combined: "[c1] - (code1)" },
{ friendly: "code2", combined: "[c2] - (code2)" },
{ friendly: "code3", combined: "[c3] - (code3)" },
{ friendly: "code4", combined: "[c4] - (code4)" }
];
const selectedOptions = [
{ friendly: "code1", combined: "[c1] - (code1)" },
{ friendly: "code2", combined: "[c2] - (code2)" }
];
this.setState({
availableOptions,
selectedOptions: selectedOptions
});
};
handleChange = (event, values) => {
const selectedOptions = event ? event.target.value : values;
this.setState({ selectedOptions });
};
menuItems = () => {
const { availableOptions } = this.state;
return availableOptions.map(optionName => {
return (
<MenuItem value={optionName}>
<ListItemText primary={optionName.friendly} />
</MenuItem>
);
});
};
render() {
const { selectedOptions } = this.state;
return (
<FormControl>
<Select
multiple
value={selectedOptions}
onChange={this.handleChange}
renderValue={() => selectedOptions.map(el => el.friendly).join(", ")}
children={this.menuItems()}
/>
</FormControl>
);
}
}