ListItem onPress 无法正常工作

ListItem onPress not working as it should

我正在使用 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',
  },
});

想通了:

我在列表对象中创建了每个正确的方法:

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()} 

onPress 必须是一个方法。您需要通过将列表本身绑定到列表中来使列表导航成为一种方法。例如

nav : () => {console.log("Logout pressed")}

你还需要在 onPress 中调用它。

onPress : item.nav() // Note the brackets. 

编码愉快。