起因
在用Modal
组件时,遇到无法按下android的返回键进行隐藏的效果。
特别是进行了BackHandler
注册和多次测试之后还无果。。
发现
于是四处寻找原因,最终在官方issue上找到一段:
Android Modal doesn't handle the back button
分析
经过分析,发现并不需要使用BackHandler
API进行注册使用,直接调用Modal
的一个props
:onRequestClose
。
这个prop
,在Android
上按下返回键的时候会调用,所以,我们只需要在这个方法里边设置隐藏Modal
即可。
测试
简单写一段测试代码,经测试,完美达到预期效果:
import React, { Component } from "react";
import {
View,
Text,
Modal
} from "react-native";
import PropTypes from "prop-types";
export default class Market extends Component {
static propTypes = {}
static defaultProps = {}
constructor (props) {
super(props);
this.state = {
visible: false
}
}
render () {
return (
<Modal
visible={this.state.visible}
onRequestClose={this.hide.bind(this)}
onShow={() => null}
transparent={true}
animationType="none">
<View>
<Text>market</Text>
</View>
</Modal>
)
}
show () {
this.setState({ visible: true });
}
hide () {
this.setState({ visible: false });
}
}
重点:
onRequestClose={this.hide.bind(this)}
网友评论