0

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

2 回答 2

1

弄清楚了:

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

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()} 
于 2017-04-29T09:56:14.377 回答
1

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

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

您还需要从 onPress 调用它。

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

快乐编码。

于 2017-04-29T19:57:18.753 回答