1

我想要一个带有类别列表的侧边菜单,当用户选择一个类别时,它应该打开一个可滚动列表,位于类别名称的正下方,其中包含该类别的所有部分。

所以我创建了两个列表组件,一个用于类别(SideMenuList),一个用于家具。我想当用户选择类别时,我需要使用条件渲染来渲染第二个列表。

我的代码:

来自 app.js 的侧边菜单代码

state = {
  hideMenu: null,
  hideList: null
}

sideMenuShow() {

     if(!this.state.hideMenu) {
        return(
        <SideMenu> 
          <MenuButton onPress = {() => this.setState({hideMenu: true})}/>
          <Text style = {{color: 'white', fontSize: 16, fontWeight: 'bold'}}>Furniture</Text>
          <SideMenuList onPress = {() => this.setState({hideList: true})}>
            {
              this.state.hideList ? console.log('yes') : null
            }
          </SideMenuList>
        </SideMenu>
        ); 
      }
     else {
         return(
          <SmallSideMenu> 
            <MenuButton onPress = {() => this.setState({hideMenu: false})}/>
          </SmallSideMenu>
         );
     }
 }

SideMenuList.js

import React, { Component } from 'react';
import { View, FlatList, Text, TouchableOpacity } from 'react-native';
import { CardSection } from './common';
import SideMenuItem from './SideMenuItem';

class SideMenuList extends Component {

render()  {
    return (
        <View style = {{flex: 1}}>
          <FlatList
            style = {{marginBottom: 2}} 
            data={[
            {key: 'Test'},
            {key: 'Test2'},
            {key: 'Test3'},
            {key: 'Test4'},
            {key: 'Test5'}
            ]}
          renderItem={({item}) => 
          <TouchableOpacity>
              <SideMenuItem 
              onPress = {this.props.onPress}
              text={item.key}
              >
              {this.props.children}
              </SideMenuItem>
          </TouchableOpacity>}
        />
      </View>
    );
  }
}

export default SideMenuList;

SideMenuItem.js 代码

import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

const SideMenuItem = (props, {onPress}) => {
return (  
  <View 
  style = {{flex: 1}}>
  <TouchableOpacity
  onPress = {onPress}>
    <Text style={styles.itemStyle}>{props.text}</Text>
  </TouchableOpacity>
  {props.children}
  </View>
);
}

const styles = {
  itemStyle: {
    marginTop: 10,
    marginRight: 20,
    marginLeft: 10,
    color: 'white' 
   }
};

export default SideMenuItem;

我现在的问题是我的 onPress 事件没有改变我的状态属性“hideList”的值,所以我什至无法检查我的解决方案是否真的有效。当值为 true 但它从未出现在我的控制台中时,我正在做一个控制台日志。

提前致谢。

4

1 回答 1

1

您正在渲染您SideMenuItemTouchableOpacity包装(在您的 SideMenuList 文件中)。

可能当您按下按钮时,它会触发 SideMenuList 按钮,而不是 SideMenuItem 按钮。

尝试TouchableOpacity从 SideMenuList 中删除并检查它是否有效。

希望能帮助到你

于 2018-04-11T16:26:46.993 回答