React Native创建侧边菜单报错:can't find variable: drawer_width
Hey there, let's get that can't find variable: drawer_width error sorted out for your React Native side drawer. The root issue here is that the react-native-side-drawer component expects a drawer_width variable to exist in your code (it uses this to calculate the drawer's size), but you haven't defined it yet.
Here's how to fix it step by step:
1. Add the missing variable with a dynamic value
First, we'll use React Native's Dimensions API to get the device's screen width, then calculate the drawer width to match the drawerPercentage={45} you already set. This ensures the drawer looks consistent across different devices.
2. Update your full code
Here's the revised code with the missing variable added and all necessary fixes:
import React from 'react' import { View, Text, StyleSheet, TouchableOpacity, Dimensions } from 'react-native' import MenuDrawer from 'react-native-side-drawer' // Define the drawer width based on 45% of the screen width const drawer_width = Dimensions.get('window').width * 0.45; class Example extends React.Component { constructor(props) { super(props); this.state = { open: false }; } toggleOpen = () => { this.setState({ open: !this.state.open }); }; drawerContent = () => { return ( <TouchableOpacity onPress={this.toggleOpen} style={styles.animatedBox}> <Text>Close</Text> </TouchableOpacity> ); }; render() { return ( <View style={styles.container}> <MenuDrawer open={this.state.open} drawerContent={this.drawerContent()} drawerPercentage={45} animationTime={250} overlay={true} opacity={0.4} drawerWidth={drawer_width} // Pass the defined width to the component > <TouchableOpacity onPress={this.toggleOpen} style={styles.body}> <Text>Open</Text> </TouchableOpacity> </MenuDrawer> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#fff", alignItems: "center", justifyContent: "center", marginTop: 30, zIndex: 0 }, animatedBox: { flex: 1, backgroundColor: "#38C8EC", padding: 10 }, body: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#F04812' } })
Key changes made:
- Added
Dimensionsto the imports fromreact-native - Defined
drawer_widthas 45% of the screen width (matches yourdrawerPercentagesetting) - Passed
drawerWidth={drawer_width}as a prop to theMenuDrawercomponent to ensure it uses the correct value
Once you update your code with these changes, the error should disappear, and your side drawer should work as expected.
内容的提问来源于stack exchange,提问作者Makame Sharif

