由于许多选择选项彼此非常相似,因此我尝试为它们创建一个组件。我读到我必须转发裁判,所以我这样做了,现在我不再有任何错误消息,选择后我的状态可以正确更新。
唯一不更新的是选择字段,该字段始终显示为空。
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;