我正在使用React Native和react-native-elements在侧边菜单中呈现选项列表,但是当我运行项目时,onPress
中的ListItem
道具无法充当这应该。运行时,三个控制台日志似乎会自动与屏幕上的主要内容进行迭代,但是当打开侧面菜单时,无法按下列表项,控制台中也不会记录任何内容。我的onPress功能有问题吗?
import { SideMenu, List, ListItem } from 'react-native-elements';
import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import { MaterialIcons } from '@expo/vector-icons';
export default class Home extends Component {
state = {
toggled: false,
}
toggleSideMenu () {
this.setState({
toggled: !this.state.toggled
})L
render() {
const list = [
{
name: 'Profile',
pic: 'assignment-ind',
//nav: this.props.navigation.navigate('Profile', { user: this.state.user })
nav: console.log('pressing Profile!'),
},
{
name: 'Settings',
pic: 'settings-applications',
nav: console.log('pressing Settings!'),
},
{
name: 'Logout',
//nav: firebase.auth().signOut() // sign user out
nav: console.log('pressing Logout!'),
}
]
const MenuComponent = (
<View style={{flex: 1, backgroundColor: 'white', paddingTop: 10}}>
<List containerStyle={{marginBottom: 20}}>
{
list.map((item, i) => (
<ListItem
onPress={() => item.nav}
leftIcon={{ name: item.pic }}
key={i}
title={item.name}
/>
))
}
</List>
</View>
);
return (
<SideMenu
menu={MenuComponent}
toggled={this.state.toggled}>
<View style={styles.container}>
<View style={{ flexDirection: 'row' }}>
<TouchableHighlight
style={{marginTop: 20, marginLeft: 9}}
onPress={this.toggleSideMenu.bind(this)}
underlayColor='transparent'>
<MaterialIcons
color='white'
name='menu'
size={28}
/>
</TouchableHighlight>
</View>
</View>
</SideMenu>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'black',
},
});
答案 0 :(得分:0)
想出来:
我在列表对象中创建了每个正确的方法:
const list = [
{
name: 'Profile',
pic: 'assignment-ind',
//nav: this.props.navigation.navigate('Profile', { user: this.state.user })
nav: () => { console.log('pressing Profile!'); },
},
{
name: 'Settings',
pic: 'settings-applications',
nav: () => { console.log('pressing Settings!'); },
},
{
name: 'Logout',
//nav: firebase.auth().signOut() // sign user out
nav: () => { console.log('pressing Logout!'); },
}
然后我在onPress
函数中添加了括号:
onPress={() => item.nav()}
答案 1 :(得分:0)
onPress必须是一种方法。您需要通过将列表绑定到其自身来使列表导航成为方法。例如。
nav : () => {console.log("Logout pressed")}
你还需要从onPress调用它。
onPress : item.nav() // Note the brackets.
快乐的编码。