繁体   English   中英

如何在响应式中进行回调

[英]how to make a callback in reactnative

我有一个要显示的对话框。 我需要一个箭头函数,该函数允许我调用已编写的回调道具以及通过使用状态关闭模式屏幕。 我可以关闭它,但不能从父组件调用回调

  export class DialogBox extends PureComponent {
  okButton = <Button type="text" title={t('action')} onPress={this.onOkPressed} />

  cancelButton = <Button type="text" title={t('cancel')} onPress={this.onCancelPressed} />

  confirmButtonBox = (
    <Fragment>
      {this.cancelButton}
      {this.okButton}
    </Fragment>
  )

  state = {
    isVisible: this.props.isVisible,
  }

  onModalClose = () => {
    this.setIsVisible(false)
  }

  onOkPressed = () => {
    this.props.onOkPress()
    this.onModalClose()
  }

  onCancelPressed = () => {
    this.props.onCancelPress()
    this.onModalClose()
  }

  setIsVisible (visible) {
    this.setState({ isVisible: visible })
  }

  renderButtons (type) {
    switch (type) {
      case 'confirm':
        return this.confirmButtonBox
      case 'alert':
        return this.okButton
      default:
        return this.okButton
    }
  }

  render () {
    const {
      title, message, type,
    } = this.props

    return (
      <Modal transparent animationType="fade" visible={this.state.isVisible}>
        <View style={styles.container}>
          <View style={styles.alertContainer}>
            <View>
              <Text>
                <H3 style={{ fontWeight: 'bold' }}>
                  {title}
                </H3>
              </Text>
              <Text>
                {message}
              </Text>
            </View>
            <View style={styles.buttons}>
              {this.renderButtons(type)}
            </View>
          </View>
        </View>
      </Modal>
    )
  }
}

我需要它工作的方式是:

我在此组件外部有一个容器类,该容器类允许用户在Ok press和onCancle press上实现回调方法。

   class DialogBoxStoryContainer extends PureComponent {
  // state = { isVisible: false, type: 'confirm' }

  onOkPressed = () => {
    // this.setState({ isVisible: false })
    console.debug('on ok pressed')
  }

  onCancelPressed = () => {
    // this.setState({ isVisible: false })
    console.debug('on cancel pressed')
  }

  render () {
    return (
      <View>
        <DialogBox
          {...this.props}
          onOkPress={this.onOkPressed}
          onCancelPress={this.onCancelPressed}
          isVisible="true"
          type="confirm"
        />

我看不到回调在这里执行。 我在这里想念什么?

您的代码对我有用。 如果未将Chrome中的“默认级别”(假设您使用的是Chrome)设置为“详细”,则看不到console.debug输出。 我不知道此配置在Firefox或其他浏览器中的位置。 因此,如果您要使用其他设备,只需找到此设置即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM