【发布时间】:2021-10-28 17:05:07
【问题描述】:
我做了一个游戏页面来响应。当您赢得一个时,它会显示一个表单对话框(使用材料 UI:https://material-ui.com/components/dialogs/#form-dialogs)。组件的可见性取决于 open 属性,当您按下按钮时,该属性会随“handleClickOpen”而改变。我想重用代码,所以我制作了一个包含对话框的组件。到目前为止,这是我的代码(子类):
class Pop_dialog extends Component {
constructor(props) {
super(props)
this.state = {
open: false
}
}
handleOpen() {
console.log('A')
this.setState({ open: true })
}
handleClose() {
console.log('B')
this.setState({ open: false })
}
render() {
return (
<Dialog open={this.state.open} onClose={this.handleClose} aria-labelledby="form-dialog-title">
<DialogTitle id="form-dialog-title">Subscribe</DialogTitle>
<DialogContent>
<DialogContentText>
To subscribe to this website, please enter your email address here. We will send updates
occasionally.
</DialogContentText>
<TextField
autoFocus
margin="dense"
id="name"
label="Email Address"
type="email"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color="primary">
Cancel
</Button>
<Button onClick={this.handleClose} color="primary">
Subscribe
</Button>
</DialogActions>
</Dialog>
)
}
我在父类的一个函数中调用“handleOpen”:
triggerDialog() { this.dialogRef.current.handleOpen(); }
render ()
{
...
<Pop_dialog ref={this.dialogRef}/>
}
在我赢/输游戏时调用 triggerDialog 函数,它会很好地打开表单对话框。当我尝试关闭它时出现问题(使用取消或订阅按钮)。页面抛出下一个错误:
我找不到它为什么在这里失败,但在它使用“handleOpen”时却没有。顺便说一句,这是我使用的第四个解决方案。我还尝试使用带有 useContext 引擎盖的功能组件(它根本不起作用),像道具一样将“打开”传递给孩子(我也可以打开对话框但不能关闭它)并在session var,在父组件中定义并在子组件中调用(我无法打开对话框)。
我不知道其中一些想法是否可行,或者我是否需要一个全新的想法。我对任何想法都持开放态度,只要它保持 Pop_dialog 可重复使用。
【问题讨论】:
-
这个问题已经回答here
标签: javascript reactjs ref