javascript - React:在父组件中调用子函数的问题
问题描述
我在反应中制作了一个游戏页面。当您赢得一个时,它会显示一个表单对话框(带有材料 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 可重用。
解决方案
似乎您没有绑定this
到Pop_dialog
. 结果是this
在回调处理程序中未定义。
在构造函数中绑定:
class Pop_dialog extends Component {
constructor(props) {
super(props)
this.state = {
open: false
}
this.handleOpen = this.handleOpen.bind(this);
this.handleClose = this.handleClose.bind(this);
}
handleOpen() {
console.log('A')
this.setState({ open: true })
}
handleClose() {
console.log('B')
this.setState({ open: false })
}
...
或者将处理程序转换为箭头函数,以便this
自动绑定类。
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 })
}
...
推荐阅读
- expo - @react-native-async-storage/async-storage 在使用 expo 生成 ipa 或 apk 时不起作用
- laravel - 在Laravel 8中将文件上传到firebase后如何获取下载链接
- .net - EF Core 迁移在更改身份 PK 数据类型时失败
- flutter - 如何将 csv 数据从文件选择器转换为动态列表?
- c# - C#:将证书链导出到 Base64 编码文件
- javascript - 我正在尝试覆盖小部件 DomainLeaf 中的函数 _getOperatorsFromType 但它没有用
- python - 在 google colab 上使用 randomsplit() 时出现 Py4JJavaError
- excel - Excel VBA中对表的动态引用
- r - 闪亮的数据表,按背景颜色过滤列(就像我们在 excel 中一样)
- java - 将带有字符串集的 Map 转换为带有字符串的 Map (Java)