首页 > 解决方案 > 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 可重用。

标签: javascriptreactjsref

解决方案


似乎您没有绑定thisPop_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 })
  }
  ...

推荐阅读