You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在点击按钮时将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:57:02