如何在点击按钮时将JSON数组的对应项展示在React Native模态框中
问题根因
你代码里的modalData是普通JS变量,没有存放在React状态中:
- 调用
SetshowStanzas(true)触发组件重渲染时,整个组件函数会重新执行,modalData会被重置为初始的空数组[] - 重渲染后读取空数组的
description属性自然会报未定义错误
修复方案
把modalData改为React状态变量即可,完整修改后的代码如下:
import { StatusBar } from "expo-status-bar"; import React, { useState } from "react"; import { Modal, Platform, SafeAreaView, ScrollView, StyleSheet, Text, View, } from "react-native"; export default function App() { const data = require("./dummyData.json"); // 把modalData改为状态变量 const [modalData, setModalData] = useState({}); const [showStanzas, SetshowStanzas] = useState(false); const onpressHandler = function (a, b) { setModalData(data[b]); SetshowStanzas(true); }; return ( <SafeAreaView style={styles.container}> <View style={styles.headingView}> <Text style={styles.heading}></Text> </View> <ScrollView> <View style={styles.container2}> <View style={styles.container3}> {data.map((datas, id) => { return ( <View key={id}> <Text style={styles.hymnTitle} onPress={() => { onpressHandler(true, id); }} > {datas.id}.{" "} {datas.title}{" "} </Text> </View> ); })} <Modal animationType={"slide"} visible={showStanzas} onRequestClose={() => { SetshowStanzas(false); // 关闭时清空状态避免残留 setModalData({}); }} > <View> <Text style={styles.desc}> {modalData.description} </Text> </View> </Modal> </View> </View> </ScrollView> </SafeAreaView> ); }
内容的提问来源于stack exchange,提问作者Wizard Chiboy
相关产品推荐
相关产品推荐

