You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native创建侧边菜单报错:can't find variable: drawer_width

Fixing "can't find variable: drawer_width" Error in react-native-side-drawer

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 Dimensions to the imports from react-native
  • Defined drawer_width as 45% of the screen width (matches your drawerPercentage setting)
  • Passed drawerWidth={drawer_width} as a prop to the MenuDrawer component 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:30:13