首页 > 解决方案 > 多项数据。使用 react-native 在动态模式中显示单击的数据

问题描述

食物> PIZZA> 点击任何披萨会打开一个模式。我想显示在此模式中单击的比萨饼的信息。我看了很多类似的例子,但我无法摆脱它。所以我需要帮助。我在下面添加了部分代码。同时,代码在expo和下面的链接中都有

小吃.expo.io/@ibrahimyolbir/e48b05

手风琴

<Accordion
  dataArray={this.state.menus}
  animation={true}
  expanded={true}
  renderHeader={this._renderHeader}
  renderContent={this._renderContent}
/>

我在渲染内容中的打开模式按钮

onPress={this.triggerModal(food)}
_renderContent = (item) => {
  return (
    <List>
      {
        item.food.map((food, index) => {
          return (
            <ListItem style={{
              backgroundColor: "#f0f0f5",
              padding: 10,
              marginLeft: 0,
              paddingRight: 10,
              fontStyle: "italic",
              listStyleType: "none",
              flexDirection: "row",
              justifyContent: "space-between"
            }}>
              <TouchableOpacity
                onPress={this.triggerModal(food)}
                style={{
                  flexDirection: "row",
                  justifyContent: "space-between"
                }}
              >
                <Left style={{
                  maxWidth: 57
                }}>
                  <Thumbnail source={require("../assets/images/left-food-icon.png")} />
                </Left>
                <Body>
                  <Text >{food.name}</Text>
                  <Text note >{food.description}</Text>
                </Body>
                <Right>
                  <Text >{food.price} :-</Text>
                </Right>
              </TouchableOpacity>
            </ListItem>
          )
        }
        )
      }
    </List>
  );
}

模态

<Modal
  style={{ marginTop: 122 }}
  isVisible={this.state.display}
  visible={this.state.display}
  onSwipeComplete={() => this.setState({ isVisible: false })}
  onSwipeThreshold={1}
  swipeDirection="down"
  animationType="slide"
  onRequestClose={() => {
    Alert.alert('Modal has been closed.');
  }}>
  <View style={{ flex: 1, backgroundColor: "#fff" }}>
    <Text>Hello!</Text>
    <TouchableOpacity onPress={this.closeDisplay} style={{ marginTop: 40, marginLeft: 150 }}>
      <Text> CLOSE MODAL </Text>
    </TouchableOpacity>

    {/* <Text> {this.state.menus} </Text> */}
  </View>
</Modal>

我的 Json 数据文件

食物屏风

标签: react-nativeexporeact-native-modal

解决方案


其中一种方法可以是:

1)创建一个新状态

currentChildData:[],
currentParentData:[],

2)在onPress事件中传递父ID和子索引

 <TouchableOpacity onPress={()=>this.triggerModal(item.id,index)}  

3)使用传递的索引和父ID,我们可以从菜单状态中提取有关(要单击的项目)的相关信息

triggerModal = (ParentIndex,childIndex) => {
    this.setState(prevState => {
    let ParentData=[...prevState.menus].find(each=>each.id==ParentIndex)
      return {
        display: true,
        currentChildData: ParentData.food[childIndex],
        currentParentData: ParentData,
      }
    });
  }

4)现在我们的状态中有(要点击的项目)的信息。然后我们可以在 Modal 中使用它(如下所示的项目名称)

 <Text>{this.state.currentChildData.name}</Text> 

工作代码:https ://snack.expo.io/By_QVbPMI


推荐阅读