我想在我的组件中显示一个对话框,但我希望此对话框作为单独的组件,例如:
function MyComponent() {
const [openDialog, setOpenDialog] = useState(false);
const handleOpenDialog = () => {
setOpenDialog(true);
};
return (
<React.Fragment>
<Button variant="contained" size="medium" onClick={handleOpenDialog}>
Open Dialog
</Button>
<CreateCategory openDialog={openDialog} />
<Box>...</Box>
</React.Fragment>
);
}
对话就像:
export default function CreateCategory(props) {
const [openDialog, setOpenDialog] = useState(props.openDialog);
const [newCategoryName, setNewCategoryName] = useState("");
const handleDialogClose = () => {
setOpenDialog(false);
};
const handleAddCategory = (categoryName) => {...};
const handleCategoryNameChange = (e) => {
setNewCategoryName(e.target.value);
};
return (
<React.Fragment>
<Dialog
fullWidth
maxWidth={"sm"}
open={openDialog}
onClose={handleDialogClose}
>
<DialogTitle>Create Video Category</DialogTitle>
<DialogContent>
<TextField
...
/>
</DialogContent>
<DialogActions>
<Button>Add Category</Button>
<Button variant="outlined" onClick={handleDialogClose}>
Close
</Button>
</DialogActions>
</Dialog>
</React.Fragment>
);
}
但是它不起作用,我想在另一个组件中重复使用对话框
我在代码沙盒中使用它https://codesandbox.io/s/quizzical-merkle-ivquu?file =/src/app.js
Rafael无缘无故地将道具归入状态,这是一个反诉讼,这引起了您的问题。
您的path状态为
openDialog
props.openDialog
// Pass the setter as well
<CreateCategory openDialog={openDialog} setOpenDialog={setOpenDialog} />
const handleDialogClose = () => {
props.setOpenDialog(false); // Use the prop.
};
<Dialog
fullWidth
maxWidth={"sm"}
open={props.openDialog} // Use value directly here
onClose={handleDialogClose}
>
在情况下,这也是以下片段中的混乱来源(无论如何您都应该删除):
const [openDialog, setOpenDialog] = useState(props.openDialog);
props.openDialog
仅在第一个渲染上用于初始化状态。将来任何时间都改变了道具,状态却不会改变以匹配它。这是一个Initial值。