javascript - 在 Modal 的子组件中设置时,不会触发 BackAndroid/BackHandler 事件监听器

标签 javascript android reactjs react-native

我无法在放置在模态内的组件中使用 native react BackHandler 设置事件监听器。我怀疑发生这种情况是因为模态正在监听在 onRequestClose Prop 上传递的方法。

好吧,我不确定这是一个错误还是一个功能请求,但我建议您允许我们将某个值(例如 null)传递给 onRequestClose Prop 作为一种方式标记可能在 Modal 的子组件中设置了 BackHandler 事件监听器,并且这些监听器具有优先级(即覆盖 Modal 的 onRequestClose)。

环境

环境:

  • 操作系统:macOS High Sierra 10.13.3
  • 节点:9.2.0
  • yarn :0.24.6
  • npm:5.6.0
  • 守望者:4.7.0
  • Xcode:Xcode 9.2 构建版本 9C40b
  • 安卓工作室:3.0 AI-171.4408382

软件包:(需要 => 安装)

  • react :16.2.0 => 16.2.0
  • native react :0.53.0

    => 0.53.0

重现步骤

下面是子组件内部的说明:

class ChildComponent extends Component {
    componentDidMount () {
        BackHandler.addEventListener('hardwareBackPress', this._onBackPress)
    }

    componentWillUnmount () {
        BackHandler.removeEventListener('hardwareBackPress', this._onBackPress)
    }

    _onBackPress = () => {
        console.log('Event was triggered')

        return true
    }

    render () {
        return (
            <Text>{'Some Text'}</Text>
        )
    }
}

export default ChildComponent

具有模态(父)的组件具有以下说明:

class ParentComponentWithModal extends Component {
    constructor (props) {
        super(props)
        this.state = {
            modalVisible: true
        }
    }

    render () {
        const { modalVisible } = this.state
        return (
            <View>
                <Modal
                    visible={modalVisible}
                    onRequestClose={() => console.log('onRequestClose')}
            >
                <ChildComponent />
            </Modal>
          </View>
        )
    }
}

export default ParentComponentWithModal

预期行为

添加到 hardwareBackPressed 监听器的 _onBackPress 方法应在按下后退按钮时执行。

实际行为

当按下后退按钮时,定义在 onRequestClose 属性上的函数被触发。即使没有在 onRequestClose 属性上定义函数,附加到在模态子项中定义的事件监听器的方法也不会执行。

最佳答案

此行为记录在 React Native's site 上:

onRequestClose The onRequestClose callback is called when the user taps the hardware back button on Android or the menu button on Apple TV. Because of this required prop, be aware that BackHandler events will not be emitted as long as the modal is open.

因此您需要使用 onRequestClose 函数而不是 BackHandler。

<Modal
   visible={visible}
   onRequestClose={() => this.setState({ visible: false })}
>

关于javascript - 在 Modal 的子组件中设置时,不会触发 BackAndroid/BackHandler 事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50199385/

相关文章:

android - 网页自动登录

javascript - 我怎样才能在 redux 中正确克隆 json 数组?

javascript - 使用 。反引号内的运算符 javascript

javascript - IE>10浏览器中通过js获取之前的URL

javascript - 将 ES6 类对象序列化为 JSON

android - 更改 float 操作按钮的形状

reactjs - Next.js 在 router.push 时保持状态或发送 props

javascript - 为什么此代码(一次删除多个项目)会在防火墙后面挂起?

javascript - 用于标记和向量的 Openlayers zIndex

android - 在Android app上获取id token并在后端服务器验证(How to use id token?)