当我们在 react native 中触摸屏幕上的任何位置时,如何隐藏侧边栏



我创建了一个自定义侧边栏,因为客户端请求需要它,我可以在按下按钮时切换侧边栏,但是,"当我按下屏幕上的任意位置时,我需要关闭侧边栏">

我尝试使用反应导航中的抽屉,但无法实现我想要的。

let width = Dimensions.get('window').width
let height = Dimensions.get('window').height
class Sample1 extends React.Component { 
constructor(){
super()
this.state = {
toggleDrawer: false
}
}
toggle = () => {
this.setState(() => ({
toggleDrawer: !this.state.toggleDrawer
}))
}
touchAnywhere = () => {
this.setState(() => ({
toggleDrawer: false
}))
}
render () {
return (
<View onPress={this.touchAnywhere}>
<TouchableOpacity onPress={this.toggle}>
<Image
source={require('../../images/drawer-150x150.png')}
style={{ width: 25, height: 25, marginLeft: "80%" }}
/>
</TouchableOpacity>
{ 
this.state.toggleDrawer && (
<View style={styles.menu}>
<SideBar 
/>
</View>
)
}
</View>
)
}
}
const styles = StyleSheet.create({
menu: {
flex: 1,
backgroundColor: 'yellow',
position : 'absolute',
left: 0,
top: 0,
width : width * 0.8, 
height : height,
paddingTop : 10,
paddingLeft : 10,
paddingRight : 10,
paddingBottom : 10
},
})

onPress 在View上不起作用,可以将View包装在TouchableWithoutFeedback内或直接使用TouchableWithoutFeedback

因此,与其使用<View onPress={this.touchAnywhere}>不如使用<TouchableWithoutFeedback onPress={this.touchAnywhere}>

您可以克隆 github 存储库或查看下面的完整代码

完整代码 :

import React from 'react';
import {
View,
TouchableOpacity,
TouchableWithoutFeedback,
Dimensions,
Text,
StyleSheet,
} from 'react-native';
let width = Dimensions.get('window').width;
let height = Dimensions.get('window').height;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
toggleDrawer: false,
};
}
toggle = () => {
this.setState({toggleDrawer: !this.state.toggleDrawer});
};
render() {
return (
<TouchableWithoutFeedback onPress={this.toggle}>
<View style={styles.container}>
<TouchableOpacity onPress={this.toggle}>
<Text>Toggle Me</Text>
</TouchableOpacity>
{this.state.toggleDrawer && (
<View style={styles.menu}>
<Text>Sidebar</Text>
</View>
)}
</View>
</TouchableWithoutFeedback>
);
}
}
const styles = StyleSheet.create({
menu: {
flex: 1,
backgroundColor: 'yellow',
position: 'absolute',
left: 0,
top: 0,
width: width * 0.8,
height: height,
paddingTop: 10,
paddingLeft: 10,
paddingRight: 10,
paddingBottom: 10,
},
container: {
flex: 1,
},
});
export default App;

最新更新