Поскольку многие из моих опций выбора очень похожи друг на друга, я попытался создать для них отдельный компонент. Я прочитал, что я должен пересылать ссылки, поэтому я сделал это, и теперь у меня больше нет сообщений об ошибках, и мое состояние корректно обновляется после выбора.
Единственное, что не обновляется, это поле выбора, которое всегда отображается пустым.
Dropdown.js
import { Select } from "@material-ui/core";
import CustomOption from "./CustomOption";
class Dropdown extends React.Component {
constructor(props) {
super(props);
this.state = {
selection: 0
};
}
handleChange = name => event => {
console.log(event.target.value);
switch (name) {
// More cases
default:
this.setState({ [name]: event.target.value });
break;
}
};
render = () => {
return (
<>
<Select
value={this.state.selection}
onChange={this.handleChange("selection")}
>
<CustomOption text="A" value={0} testValue={2} />
<CustomOption text="B" value={1} testValue={2} />
<CustomOption text="C" value={2} testValue={1} />
<CustomOption text="D" value={3} testValue={2} />
</Select>
<br />
<br />
{this.state.selection}
</>
);
};
}
export default Dropdown;
CustomOption.js
import React from "react";
import { ListItemText, MenuItem } from "@material-ui/core";
const DropdownEntry = React.forwardRef((props, ref) => {
if (props["data-value"] > props.testValue) {
return (
<MenuItem disabled ref={ref} {...props}>
<ListItemText>{props.text}</ListItemText>
</MenuItem>
);
}
// User may select this option
return (
<MenuItem ref={ref} {...props}>
<ListItemText>{props.text}</ListItemText>
</MenuItem>
);
});
export default DropdownEntry;
Codesandbox: https://codesandbox.io/s/us4ml