【发布时间】:2022-09-23 20:28:15
【问题描述】:
我有一个案例,我有 3 个项目,在第一个项目的情况下,它应该只显示第一个项目,并且不允许用户选择第二个和第三个,但如果 isItFirt = false 那么用户应该能够从列表中进行选择。我编写了最小的可重现示例,如下所示:
import * as React from \"react\";
import {
Typography,
Button,
Dialog,
Box,
Select,
InputLabel,
FormControl,
MenuItem,
SelectChangeEvent
} from \"@mui/material\";
enum MyOptions {
FIRST = 1,
SECOND = 2,
THIRD = 3
}
export default function App() {
const [open, setOpen] = React.useState(true);
const [myOptions, setMyOptions] = React.useState(MyOptions.SECOND as number);
const handleChange = (event: SelectChangeEvent) => {
let nr = parseInt(event.target.value, 10);
setMyOptions(nr);
};
const isItFirst: boolean = false;
const handleClose = () => {
setOpen(false);
};
const somethingHappens = () => {
console.log(\"clicked: \", myOptions);
setOpen(false);
};
React.useEffect(() => {
if (isItFirst) {
setMyOptions(MyOptions.FIRST as number);
}
}, [isItFirst]);
return (
<div>
<Button
variant=\"contained\"
size=\"small\"
onClick={() => {
setOpen(true);
}}
>
Display dialog
</Button>
<Dialog
open={open}
onClose={handleClose}
aria-labelledby=\"modal-modal-title\"
aria-describedby=\"modal-modal-description\"
>
<Box>
<Typography id=\"modal-modal-title\" variant=\"h6\" component=\"h4\">
Select one of the options
</Typography>
<FormControl>
<InputLabel id=\"1\">Options</InputLabel>
<Select
labelId=\"\"
id=\"\"
value={myOptions}
label=\"Options\"
onChange={(e: any) => handleChange(e)}
>
{isItFirst ? (
<MenuItem value={MyOptions.FIRST}>This is first</MenuItem>
) : (
<div>
<MenuItem value={MyOptions.SECOND} key={MyOptions.SECOND}>
This is second
</MenuItem>
<MenuItem value={MyOptions.THIRD} key={MyOptions.THIRD}>
This is third
</MenuItem>
</div>
)}
</Select>
</FormControl>
</Box>
<Button
variant=\"contained\"
size=\"small\"
onClick={() => {
somethingHappens();
}}
>
Select
</Button>
</Dialog>
</div>
);
}
这是错误输出:
MUI: You have provided an out-of-range value `1` for the select component.
Consider providing a value that matches one of the available options or \'\'.
The available values are \"\".
这是isItFirst === false的情况下显示的对话框,我不明白为什么我在useEffect的帮助下设置myOptions的状态时显示为空白。
标签: javascript reactjs typescript